<template>
  <!-- start 选择组织架构页面 -->
  <div class="department-container" v-loading.fullscreen.lock="loading">
    <div class="guide-model-box" v-if="nowGuideStep < 4"></div>
    <!-- start 主要内容 -->
    <div class="department-main">
      <div
        v-show="!collapse"
        class="department-left department-state"
      >
        <div class="dept-search">
          <el-input
            v-model="deptKeyword"
            :placeholder="$t('department.organizational.mainContent.placeholder')"
            @change="debounceDept"
          >
            <i slot="prefix" class="el-input__icon el-icon-search"></i>
          </el-input>
          <!--
            @input="debounceDept"
            @keyup.enter.native="debounceDept"
            <div class="dept-add" @click="addDepartment(true)">
                <i class="iconfont icon-add2"></i>
              </div> -->
        </div>
        <div class="el-tabs__content">
          <div >
            <el-button
              type="primary"
              @click="openImportWechatContact"
              class="base-button"
              v-if="isOpenData && isSystemManager && isWhiteList"
              :class="{ 'sync-button': !collapse }"
            >
              {{ $t('department.organizational.mainContent.importWXAddress') }}
              <el-tooltip placement="top">
                <template slot="content">
                  {{ $t('department.organizational.mainContent.tipWX') }}
                </template>
                <i class="iconfont icon-question"></i>
              </el-tooltip>
            </el-button>
          </div>
          <div class="h-100-p scroll-y dept-scroll-box">
            <!-- start 同步微信通讯录 -->
            <el-button
              type="primary"
              @click="synchronousWeChat"
              :loading="synchronousState"
              class="base-button"
              v-if="tenantType == 2 || tenantType == 3"
              :class="{ 'sync-button': !collapse }"
            >
              {{ synchronousState ? $t('common.base.syncing') : $t('department.organizational.mainContent.asyncWXAddress') }}
            </el-button>
            <!-- end 同步微信通讯录 -->
            <!-- start 同步钉钉通讯录 -->
            <el-button
              v-if="tenantType == 0 && hasStaffAuth"
              class="base-button"
              :class="{ 'sync-button': !collapse }"
              type="primary"
              :loading="synchronousState"
              @click="syncDingTalkAddressBook"
            >
              {{ synchronousState ? $t('common.base.syncing') : $t('department.organizational.mainContent.asyncDDAddress') }}
            </el-button>
            <!-- end 同步钉钉通讯录 -->
            <!-- start 同步飞书通讯录 -->
            <el-button
              v-if="tenantType == 4"
              class="base-button"
              :class="{ 'sync-button': !collapse }"
              type="primary"
              :loading="synchronousState"
              @click="synchronousFeiShu"
            >
              {{ synchronousState ? $t('common.base.syncing') : $t('department.organizational.mainContent.asyncFSAddress') }}
            </el-button>
            <!-- end 同步飞书通讯录 -->

            <!-- 部门搜索框 -->

            <!-- start 左侧部门列表 -->
            <div class="department-main-left" :class="{'department-main-left-dd': tenantType == 0}">
              <!-- start 部门列表树 -->
              <div class="department-tree-view">
                <div class="bc-dept" v-if="depts.length > 0">

                  <base-tree-dept
                    expand
                    :data="depts"
                    :selected="[selectedDept]"
                    :show-checkbox="allowCheckDept"
                    @node-selected="initDeptUser"
                    :node-render="nodeRender"
                  />
                </div>
              </div>
              <div v-if="tenantType == 0">
              <el-checkbox
                v-model="isAllotByDept"
                @change="setUsedAllot"
                class="dept-header-see"
              >
                {{ $t('department.organizational.mainContent.screenDD') }}
                <el-popover
                  placement="bottom-end"
                  width="300"
                  trigger="hover"
                  :content="$t('department.organizational.mainContent.screenDDContent')"
                >
                  <i class="iconfont icon-help" slot="reference"></i>
                </el-popover>
              </el-checkbox>
            </div>
            <div v-if="tenantType == 2">
              <el-checkbox
                v-model="isAllotByDept"
                @change="setUsedAllot"
                class="dept-header-see"
              >
                {{ $t('department.organizational.mainContent.screenWX') }}
                <el-popover
                  placement="bottom-end"
                  width="300"
                  trigger="hover"
                  :content="$t('department.organizational.mainContent.screenWXContent')">
                  <i class="iconfont icon-help" slot="reference"></i>
                </el-popover>
              </el-checkbox>
            </div>
            <div>
              <el-checkbox
                v-model="isSeeAllOrg"
                @change="setSeeAllOrg"
                :disabled="isAllotByDept"
                class="dept-header-see"
              >
                {{ $t('department.organizational.mainContent.hidenOtherUser') }}
                <el-popover
                  placement="bottom-end"
                  width="300"
                  trigger="hover"
                  :content="hideOtherUserContent"
                >
                  <i class="iconfont icon-help" slot="reference"></i>
                </el-popover>
              </el-checkbox>
            </div>
              <!-- end 部门列表树 -->
            </div>
            <!-- end 左侧部门列表 -->
            <!-- v-if="tenantType == 0" -->

            <!-- <div v-if="tenantType == 2">
              <el-checkbox
                v-model="isNickname"
                @change="setNickname"
                class="dept-header-see"
              >使用企业微信姓名作为账户名称显示</el-checkbox>
              <el-popover
                placement="bottom-end"
                width="300"
                trigger="hover"
                content="开启后，使用账户的企业微信名称作为售后宝系统内账户名称；关闭后，需要手动维护账号名称"
              >
                <i class="iconfont icon-help" slot="reference"></i>
              </el-popover>
            </div> -->
          </div>
        </div>
        <div
          class="dept-step-1-box"
          :style="nowGuideStep == 0 ? 'width: 120px;height: 100px;' : ''"
          id="v-dept-step-0"
        >
          <div v-if="nowGuideStep == 0" style="position: relative">
            <div class="guide-disable-cover"></div>
          </div>
        </div>
        <div
          class="dept-step-1-box"
          :style="nowGuideStep == 4 ? 'width: 280px;height: 100px;' : ''"
          id="v-dept-step-4"
        >
          <div v-if="nowGuideStep == 4" style="position: relative">
            <div class="guide-disable-cover"></div>
          </div>
        </div>

        <div
          v-if="hasStaffAuth && isAuthStaff"
          class="department-child-item dept-role-item dept-del-role-item"
          :class="{
            'department-role-selected': selectedRole.id == -1,
            'dept-del-role-item-expand': !collapse
          }"
          @click="chooseDelRole()"
        >
          <span>{{ $t('department.organizational.mainContent.delAccounted') }} &nbsp;&nbsp;</span>
          <i class="iconfont icon-arrowright"></i>
        </div>
      </div>

      <!-- 组织架构伸缩 -->
      <div class="collapse flex-x al-c">
        <div
          @click="btnCollapse('left')"
          v-show="collapseLeft"
          class="base-collapse-btn-left"
        >
          <i class="iconfont icon-mianbanjiantou"></i>
        </div>
        <div
          @click="btnCollapse('rigth')"
          v-show="collapseRight"
          class="base-collapse-btn-right"
        >
          <i class="iconfont icon-mianbanjiantou"></i>
        </div>
      </div>
      <!-- start 右侧已删除账号 -->
      <div
        v-if="activeName === 'role'"
        class="department-main-right department-main-right_bgFFF"
        v-loading.fullscreen.lock="roleLoading"
      >
        <!-- start 角色人员 -->
        <div class="department-user-block margin-top-0">
          <div class="dept-search-group">
            <el-input
              v-model="roleKeyword"
              :placeholder="$t('department.organizational.mainContent.gcTable.placeholder')"
              style="width: 200px"
              @input="searchRole"
            >
              <i slot="prefix" class="el-input__icon el-icon-search"></i>
            </el-input>
          </div>

          <div class="department-user-table">
            <el-table
              v-table-style
              :data="rolePage.list"
              border
              @select="roleSelectionHandle"
              @select-all="roleSelectionHandle"
              :highlight-current-row="false"
              show-overflow-tooltip
              stripe
              header-row-class-name="common-list-table-header__v2"
              ref="roleMultipleTable"
              class="team-table bbx-normal-list-box"
              :height="delTableContainerHeight"
            >
              <template slot="empty">
                <BaseListForNoData
                  v-show="!roleLoading"
                  :notice-msg="$t('department.organizational.mainContent.gcTable.empty')"
                ></BaseListForNoData>
              </template>
              <el-table-column
                v-if="selectedRole.id != -1"
                type="selection"
                width="48"
                align="center"
                class-name="select-column"
              ></el-table-column>
              <el-table-column prop="workNo" :label="$t('common.label.employeeNumber')" width="120px" show-overflow-tooltip/>
              <el-table-column prop="displayName" :label="$t('common.base.fullName')" width="180px">
                <div style="display: flex" slot-scope="scope">
                  <span
                    href="javascript:;"
                    @click="goUserDetail(scope.row.userId)"
                    :class="globalIsHaveAccountViewAuth ? 'view-detail-btn' : 'view-detail-btn-disabled'"
                  >
                    <template v-if="isOpenData">
                      <open-data type="userName" :openid="scope.row.staffId"></open-data>
                    </template>
                    <template v-else>
                      {{ scope.row.displayName }}
                    </template>
                  </span>

                  <span v-if="scope.row.isTeamLeader" class="super-admin-label">{{ $t('common.label.leader') }}</span>
                  <span
                    v-if="scope.row.superAdmin == 2"
                    class="super-admin-label"
                  >{{ $t('common.label.admin') }}</span
                  >
                  <div
                    style="display: flex"
                    v-if="scope.row.labelList && scope.row.labelList.length"
                  >
                    <span
                      v-for="item in scope.row.labelList"
                      :key="item.id"
                      class="super-admin-label super-admin-label-auto"
                    >{{ item.tagName }}</span
                    >
                  </div>
                </div>
              </el-table-column>
              <el-table-column
                prop="loginName"
                :label="$t('common.label.account')"
                v-if="tenantType == 1"
              />
              <template v-if="selectedRole.id == -1">
                <el-table-column :label="$t('common.label.delTime')" width="180px">
                  <template slot-scope="scope">{{
                    scope.row.deleteTime | fmt_datetime
                  }}</template>
                </el-table-column>
                <el-table-column
                  :label="$t('common.label.unfinishEvent')"
                  width="120px"
                  v-if="!isBasicEditionHideEvent"
                >
                  <template v-if="scope.row.eventCount" slot-scope="scope">
                    <a
                      href
                      class="text-center"
                      @click.stop.prevent="
                        createTransTab('event', scope.row.userId)
                      "
                    >{{ scope.row.eventCount }}</a
                    >
                  </template>
                </el-table-column>
                <!-- 纯客服云版本不显示未完成工单 -->
                <el-table-column v-if="_isShowTaskModule" :label="$t('common.label.unfinishTask')" width="120px">
                  <template v-if="scope.row.taskCount" slot-scope="scope">
                    <a
                      href
                      class="text-center"
                      @click.stop.prevent="
                        createTransTab('task', scope.row.userId)
                      "
                    >{{ scope.row.taskCount }}</a
                    >
                  </template>
                </el-table-column>
                <el-table-column :label="$t('common.label.responsibleCustomerCount')" width="120px">
                  <template v-if="scope.row.customerCount" slot-scope="scope">
                    <a
                      href
                      class="text-center"
                      @click.stop.prevent="
                        createTransTab('customer', scope.row.userId)
                      "
                    >{{ scope.row.customerCount }}</a
                    >
                  </template>
                </el-table-column>
                <!-- 纯客服云版本不显示个人备件库 -->
                <el-table-column
                  :label="$t('common.label.personalSparePartStore')"
                  width="120px"
                  v-if="!isBasicEditionHidePart && _isShowSparePartPerson"
                >
                  <template v-if="scope.row.spareCount" slot-scope="scope">
                    <a
                      href
                      class="text-center"
                      @click.stop.prevent="
                        createTransTab('stock', scope.row.userId)
                      "
                    >{{ scope.row.spareCount }}</a
                    >
                  </template>
                </el-table-column>
                <el-table-column :label="$t('common.label.approveCount')" width="120px">
                  <template v-if="scope.row.unApproveCount" slot-scope="scope">
                    <a
                      href
                      class="text-center"
                      @click.stop.prevent="
                        createTransTab('approve', scope.row.userId)
                      "
                    >{{ scope.row.unApproveCount }}</a
                    >
                  </template>
                </el-table-column>
                <el-table-column :label="$t('common.label.deleteReason')" width="180px">
                  <template slot-scope="scope">
                    <template v-if="scope.row.show">
                      {{ $t('department.organizational.mainContent.gcTable.delete') }}
                    </template>
                    <template v-else>
                      {{ $t('department.organizational.mainContent.gcTable.rangeDelete') }}
                    </template>
                  </template>
                </el-table-column>
                <el-table-column :label="$t('common.base.table.col.operator')" width="130px" fixed="right">
                  <template slot-scope="scope">
                    <el-button
                      v-if="scope.row.show"
                      type="text"
                      @click="resume(scope.row.userId)"
                    >
                      {{ $t('common.base.revert') }}
                    </el-button>
                    <el-popover
                      v-else
                      placement="top-start"
                      width="200"
                      trigger="hover">
                      {{ $t('department.organizational.mainContent.gcTable.unrevert') }}
                      <el-button
                        slot="reference"
                        type="text"
                        class="disable-text"
                      >
                        {{ $t('common.base.revert') }}
                      </el-button>
                    </el-popover>
                    <el-button
                      v-if="
                        scope.row.eventCount ||
                          scope.row.taskCount ||
                          scope.row.customerCount ||
                          scope.row.unApproveCount ||
                      scope.row.spareCount"
                      type="text"
                      class="transfer-btn"
                      @click="createTransTab('event', scope.row.userId)"
                    >
                      {{ $t('department.organizational.mainContent.gcTable.move') }}
                    </el-button>
                    <el-popover
                      v-else
                      placement="top-start"
                      width="150"
                      class="disable-popover"
                      trigger="hover">
                        {{ $t('department.organizational.mainContent.gcTable.unmove') }}
                      <el-button
                        slot="reference"
                        type="text"
                        class="disable-text"
                      >
                        {{ $t('department.organizational.mainContent.gcTable.move') }}
                      </el-button>
                    </el-popover>
                  </template>
                </el-table-column>
              </template>
              <template v-else>
                <el-table-column :label="$t('common.label.department')" show-overflow-tooltip>
                  <template slot-scope="scope">{{
                    scope.row.tagList &&
                      scope.row.tagList
                        .map(i => (i && i.tagName) || '')
                        .join('，')
                  }}</template>
                </el-table-column>
                <el-table-column prop="cellPhone" :label="$t('common.label.phone')" />
                <el-table-column prop="enabled" :label="$t('common.label.status')">
                  <template slot-scope="scope">{{
                    scope.row.enabled == 1 ? $t('common.base.enable') : $t('common.base.deactivate')
                  }}</template>
                </el-table-column>
              </template>
            </el-table>
            <div class="table-footer bbx-normal-table-footer">
              <div class="list-info">
                <i18n path="common.base.table.totalCount">
                  <span place="count" class="level-padding">{{ rolePage.total }}</span>
                </i18n>
                <span v-show="selectedRole.id != -1">
                  <i18n path="common.base.table.selectedNth">
                    <span place="count" class="level-padding">{{ rolePage.total }}</span>
                  </i18n>
                </span>
              </div>
              <el-pagination
                class="customer-table-pagination"
                :pager-count="tenantType==0?5:7"
                background
                @current-change="roleJump"
                @size-change="roleHandleSizeChange"
                :page-sizes="defaultTableData.defaultPageSizes"
                :page-size="roleParams.pageSize"
                :current-page="roleParams.pageNum"
                layout="prev, pager, next, sizes, jumper"
                :total="rolePage.total"
              ></el-pagination>
            </div>

          </div>




        </div>
        <!-- end 角色人员 -->
      </div>
      <!-- end 右侧已删除账号 -->
      <!-- start 右侧子部门 人员列表 -->
      <div v-else class="department-main-right">
        <!-- start 部门 header -->
        <div ref="tableHeaderContainer" class="department-detail-header mar-b-10">
          <div
            class="department-detail-header-title department-detail-header-title-box"
            v-if="Object.keys(selectedDept).length > 0"
          >
            <span class="title">
              {{ deptInfo.tagName }}
            </span>
            <div class="dept-edit-del" id="v-dept-step-1">
              <div class="guide-disable-cover" v-if="nowGuideStep == 1"></div>

              <el-button
                type="plain-third"
                @click="openDepartmentEditPanel(selectedDept)"
                v-if="allowTagEdit"
              >
                <i class="iconfont icon-edit-square"></i>
                {{ $t('common.base.edit')}}
              </el-button>
              <el-button type="plain-third" @click="delDepartment()"
                            v-if="!isRootDepartment(selectedDept) && allowTagDelete">
                <i class="iconfont icon-delete"></i>
                {{ $t('common.base.delete')}}
              </el-button>
              <el-button size="small" type="primary" @click="addAdmin()"
              >{{ $t('department.organizational.mainContent.home')}}</el-button
              >
            </div>
          </div>

          <el-row class="dept-info">
            <el-col :span="8" class="form-view-col">
              <el-tooltip placement="top" v-if="teamLeadersName">
                <div slot="content">
                  <template v-if="isOpenData && deptInfo.teamLeaders && deptInfo.teamLeaders.length">
                    
                    <template v-for="(item, index) in deptInfo.teamLeaders">
                      <open-data :key="item.staffId" type="userName" :openid="item.staffId">
                      </open-data>
                      
                      <template v-if="index < deptInfo.teamLeaders.length - 1">
                        ，
                      </template>
                    </template>
                    
                  </template>
                  <template v-else>
                    {{ teamLeadersName }}
                  </template>
                </div>
                <p class="form-view-col-content">{{ `${$t('common.label.departmentLeader')}：`}}
                  <template v-if="isOpenData && deptInfo.teamLeaders && deptInfo.teamLeaders.length">
                    
                    <template  v-for="(item, index) in deptInfo.teamLeaders">
                      
                      <open-data :key="item.staffId" type="userName" :openid="item.staffId">
                      </open-data>
                      
                      <template v-if="index < deptInfo.teamLeaders.length - 1">
                        ，
                      </template>
                      
                    </template>
                    
                  </template>
                  <template v-else>
                    {{ teamLeadersName }}
                  </template>
                </p>
              </el-tooltip>
              <p v-else>{{ `${$t('common.label.departmentLeader')}：`}}</p>
            </el-col>

            <el-col :span="8" class="form-view-col">

              <div
                v-if="!deptArea"
                class="form-view-row-content"
              >
                <span class="form-view-col-content">{{$t('common.label.principalLocation')}}</span>
              </div>
              <el-tooltip v-else placement="top">
                <div slot="content">
                  {{deptArea}}
                </div>
                <span class="form-view-col-content">{{$t('common.label.principalLocation')}}：{{ deptArea }}</span>
              </el-tooltip>
            </el-col>
            <el-col :span="8" class="form-view-col">

              <el-tooltip
                v-if="deptInfo.description && deptInfo.description.length > 10"
                placement="top"
              >
                <div slot="content">{{ deptInfo.description }}</div>
                <p class="form-view-col-content">{{$t('common.label.departmentDesc')}}：{{ deptDescription }}</p>
              </el-tooltip>
              <div v-else class="form-view-row-content">
                <p class="form-view-col-content">{{$t('common.label.departmentDesc')}}：{{ deptInfo.description }}</p>
              </div>
            </el-col>
          </el-row>
          <el-row class="dept-info">
            <el-col :span="8" class="form-view-col">
              {{`${$t('common.base.contactNumber')}：`}} {{ deptInfo.phone }}
            </el-col>

            <el-col :span="16" class="form-view-col">
              <div style="width:100%">

                <el-tooltip
                  class="form-view-row-content form-view-row-content-address"
                  v-if="deptInfo.tagAddress&&deptInfo.tagAddress.longitude"
                  placement="top-start"
                >
                  <div slot="content">{{ deptSiteAddressNameObj | fmt_address }}</div>

                  <p
                    @click="openMap"
                    class="form-view-row-content form-view-row-content-address form-view-col-content"
                  ><span class="form-view-col-content-address">{{$t('common.label.departmentLocation')}}：</span><i
                    v-if="
                      deptInfo.tagAddress.longitude &&
                        deptInfo.tagAddress.latitude
                    "
                    class="iconfont icon-address team-address-icon link-text"
                  ></i>{{ deptSiteAddressNameObj | fmt_address }}</p
                  >

                </el-tooltip>
                <p v-else>{{$t('common.label.departmentLocation')}}：</p>
              </div>
            </el-col>
          </el-row>
          <!-- TODO: 面包屑列表 -->
        </div>
        <!-- end 部门 header -->

        <el-tabs
          class="dept-tabs flex-1"
          v-model="activeName1"
          @tab-click="handleClick1"
        >
          <el-tab-pane :label="$t('common.label.memberMessage')" name="user">
            <!-- start 部门人员 -->
            <div class="department-user-block">
              <!-- 只要根部门显示 -->
              <LoginUserBan v-if="haveUserNote && (selectedDept && !selectedDept.parentId)" mode="dept"></LoginUserBan>
              <div class="dept-search-group">
                <div class="flex-x">
                  <el-button size="small" v-if="allowAccountCreate" type="primary" @click="chooseUser()"
                  >{{$t('common.label.addMember')}}</el-button
                  >
                  <el-button
                    size="small"
                    type="primary"
                    @click="openCreateUserPanel()"
                    v-if="tenantType == 1 && allowAccountCreate"
                  ><i style="margin-right:6px" class="iconfont icon-add2"></i>{{$t('common.label.createAccount')}}</el-button
                  >
                  <el-button type="plain-third"
                                v-if="canRemove && allowAccountDelete"
                                @click="userDeleteConfirm('multiple')">
                    {{$t('common.label.removeMember')}}
                  </el-button>
                  <el-dropdown trigger="click" :key="moreDropDownComponentKey" style="padding: 0;margin-left: 12px;">
                    <el-button type="plain-third" v-if="isButtonDisplayed && (allowAccountImport || allowAccountExport || allowAccountStop || (canRemove && allowAccountDelete))">
                      {{$t('common.base.moreOperator')}} <i class="iconfont icon-caidanjiantou-zhankai"></i>
                    </el-button>
                  
                  <el-dropdown-menu slot="dropdown">
                    <el-dropdown-item v-if="isButtonDisplayed && allowAccountExport">
                      <div @click="exportAccount()">{{$t('common.label.exportAccount')}}</div>
                    </el-dropdown-item>

                    <el-dropdown-item v-if="isButtonDisplayed && allowAccountExport">
                      <div @click="exportAccount('all')">{{$t('common.base.exportAll')}}</div>
                    </el-dropdown-item>

                    <el-dropdown-item v-if="isButtonDisplayed && allowAccountExport">
                      <div @click="exportFeed()">{{$t('department.label.importSelect')}}</div>
                    </el-dropdown-item>

                    <!-- <el-dropdown-item v-if="isButtonDisplayed">
                      <div @click="exportFeed('all')">导出全部动态</div>
                    </el-dropdown-item> -->
                    <el-dropdown-item v-if="tenantType==1 && isButtonDisplayed && allowAccountImport">
                      <div @click="openAccountModal">{{$t('common.label.importAcount')}}</div>
                    </el-dropdown-item>
                    <el-dropdown-item v-if="isButtonDisplayed && allowAccountImport">
                      <div @click="openUpdateModal">{{$t('common.base.batchUpdate')}}</div>
                    </el-dropdown-item>
                    <el-dropdown-item v-show="canRemove && isButtonDisplayed && allowAccountDelete">
                      <div @click="userDeleteConfirm('multiple')">{{$t('common.base.batchDelete')}}</div>
                    </el-dropdown-item>
                    <el-dropdown-item v-if="isButtonDisplayed && allowAccountStop">
                      <div @click="actionMany('enable')">{{$t('common.base.batchEnable')}}</div>
                    </el-dropdown-item>
                    <el-dropdown-item v-if="isButtonDisplayed && allowAccountStop">
                      <div @click="actionMany('unable')">{{$t('common.base.batchDeactivate')}}</div>
                    </el-dropdown-item>
                    <!-- <el-dropdown-item v-if="productV2Gray">
                      <div @click="openWxDialog">维护微信</div>
                    </el-dropdown-item>
                    <el-dropdown-item>
                      <div @click="openTelDialog">维护电话</div>
                    </el-dropdown-item> -->
                  </el-dropdown-menu>
                </el-dropdown>
                </div>
                <div class="flex-x">
                  <el-input
                    v-model="keyword"
                    :placeholder="$t('common.placeholder.inputMemberSearch')"
                    style="width: 200px;margin-right:12px"
                    @change="search"
                  >
                    <i slot="prefix" class="el-input__icon el-icon-search"></i>
                  </el-input>
                  <!-- 高级搜索 -->
                  <div class="advanced-search-btn pointer" @click.self.stop="panelSearchAdvancedToggle">
                    <i class="iconfont icon-filter"></i>
                    {{$t('common.base.advancedSearch')}}
                  </div>
                </div>
              </div>

              <div
                class="department-user-table"
                v-loading="!loading && userLoading"
              >
                <el-table
                  v-table-style
                  border
                  :data="userPage.list"
                  @select="handleSelection"
                  @select-all="handleSelection"
                  @header-dragend="headerDragend"
                  :highlight-current-row="false"
                  header-row-class-name="common-list-table-header__v2"
                  stripe
                  ref="multipleTable"
                  :height="tableContainerHeight"
                  class="team-table bbx-normal-list-box information-table"
                  :key="departmentUserTableKey"

                >
                  <template slot="empty">
                    <BaseListForNoData
                      v-show="!userLoading && !userPage.list.length"
                      :notice-msg="$t('department.label.noChildMember')"
                    ></BaseListForNoData>
                  </template>
                  <el-table-column
                    type="selection"
                    width="48"
                    align="center"
                    class-name="select-column"
                    show-overflow-tooltip
                  ></el-table-column>
                  <el-table-column prop="workNo" :label="$t('common.label.employeeNumber')" :width="tableListForWidthStashuser.workNo.width" show-overflow-tooltip/>
                  <el-table-column
                    prop="displayName"
                    :label="$t('common.base.fullName')"
                    :width="tableListForWidthStashuser.displayName.width"
                    show-overflow-tooltip
                  >
                    <div slot-scope="scope">
                      <div style="display: flex" class="table-blacklist">
                        <template v-if="isOpenData">
                          <span
                            href="javascript:;"
                            @click="goUserDetail(scope.row.userId)"
                            :class="globalIsHaveAccountViewAuth ? 'view-detail-btn' : 'view-detail-btn-disabled'"
                          >
                            <open-data type="userName" :openid="scope.row.staffId"></open-data>
                          </span>
                        </template>
                        <template v-else>
                          <span
                            href="javascript:;"
                            @click="goUserDetail(scope.row.userId)"
                            :class="globalIsHaveAccountViewAuth ? 'view-detail-btn' : 'view-detail-btn-disabled'"
                          >{{ scope.row.displayName }}</span>
                        </template>


                        <span v-if="scope.row.isTeamLeader" class="super-admin-label">{{$t('common.label.leader')}}</span>
                        <span
                          class="super-admin-label"
                          v-if="scope.row.superAdmin == 2"
                        >{{$t('common.label.admin')}}</span
                        >
                        <div
                          style="display: flex"
                          v-if="
                            scope.row.labelList && scope.row.labelList.length
                          "
                        >
                          <span
                            v-for="item in scope.row.labelList"
                            :key="item.id"
                            class="super-admin-label super-admin-label-auto"
                          >{{ item.tagName }}</span
                          >
                        </div>
                      </div>
                    </div>
                  </el-table-column>
                  <el-table-column prop="loginName" :width="tableListForWidthStashuser.loginName.width" :label="$t('common.label.account')" show-overflow-tooltip />
                  <el-table-column prop="qualificationNames" show-overflow-tooltip :width="'120px'" :label="$t('common.label.subCertifications')">
                    <template slot-scope="scope">
                      {{
                        scope.row.qualificationNames &&
                          scope.row.qualificationNames.join('，')
                      }}
                    </template>
                  </el-table-column>

                  <el-table-column prop="roleDepartment" :label="$t('common.label.ofDepartment')" :width="tableListForWidthStashuser.roleDepartment.width" show-overflow-tooltip>
                    <template slot-scope="scope">
                      {{
                        scope.row.tagList &&
                          scope.row.tagList.map(i => (i && i.tagName) || '').join('，')
                      }}
                    </template>
                  </el-table-column>

                  <el-table-column prop="role" :label="$t('common.label.role')" :width="tableListForWidthStashuser.role.width" show-overflow-tooltip>
                    <template slot-scope="scope">{{
                      scope.row.roles &&
                        getProductLineRoleNames(scope.row.roles)
                    }}</template>
                  </el-table-column>
                  <el-table-column prop="cellPhone" :width="tableListForWidthStashuser.cellPhone.width" :label="$t('common.label.phone')" show-overflow-tooltip />
                  <el-table-column prop="wechat" :width="tableListForWidthStashuser.wechat.width" :label="$t('common.base.weChat')" show-overflow-tooltip/>
                  <el-table-column v-if="_isShowEmail" prop="email" :width="tableListForWidthStashuser.email.width" :label="$t('common.label.email')" show-overflow-tooltip />
                  <el-table-column prop="enabled" :width="tableListForWidthStashuser.enabled.width" :label="$t('common.label.status')">
                    <template slot-scope="scope">{{
                      scope.row.enabled == 1 ? $t('common.base.enable') : $t('common.base.deactivate')
                    }}</template>
                  </el-table-column>
                  <el-table-column v-if="haveUserNote" prop="loginStatus" :width="tableListForWidthStashuser.loginStatus.width" :label="$t('department.label.label6')">
                    <template slot-scope="scope">
                      <div class="flex-x table-blacklist">
                        <div :class="[findThisStatusClass(scope.row)]">{{ findThisStatusDes(scope.row) }}</div>
                        <div v-if="findThisStatusShowNote(scope.row)" class="flex-x mar-l-8 cur-point color-primary" @click="noteItem('dept', scope.row)"><i class="iconfont icon-tongzhiweixuanzhong font-12-i mar-r-5"></i>{{ $t('common.base.remind') }}</div>
                      </div>
                    </template>
                  </el-table-column>
                  <el-table-column prop="createTime" :width="tableListForWidthStashuser.createTime.width" :label="$t('common.label.createTime')" show-overflow-tooltip>
                    <template slot-scope="scope">{{
                      scope.row.createTime | fmt_datetime
                    }}</template>
                  </el-table-column>
                  <el-table-column prop="workArea" :label="$t('common.base.table.col.operator')" width="120px" fixed="right" show-overflow-tooltip>
                    <template slot-scope="scope">
                      <el-dropdown class="dropdown" v-if="needDropdownTwo || (scope.row.enabled == 1 && allowAccountStop && needDropdownOne)">
                        <span class="cur-point">
                          {{$t('common.base.more')}}<i class="el-icon-arrow-down el-icon--right"></i>
                        </span>
                        <el-dropdown-menu slot="dropdown" class="lang-select-dropdown">
                          <el-dropdown-item :disabled="scope.row.pending"><div @click="openCreateUserPanel(scope.row)" v-if="allowAccountEdit">{{$t('common.base.edit')}}</div></el-dropdown-item>
                          <el-dropdown-item v-if="scope.row.enabled == 1 && allowAccountStop" :disabled="scope.row.pending"><div @click="toggleEnable(scope.row)">{{$t('common.base.deactivate')}}</div></el-dropdown-item>
                          <el-dropdown-item v-else-if="allowAccountStop" :disabled="scope.row.pending"><div @click="toggleEnable(scope.row)">{{$t('common.base.enable')}}</div></el-dropdown-item>
                          <el-dropdown-item :disabled="scope.row.pending"><div @click="deleteDeptUser(scope.row)" v-if="allowAccountDelete">{{$t('common.base.delete')}}</div></el-dropdown-item>
                          <el-dropdown-item><div @click="userResetPwdConfirm(scope.row.userId)" v-if="allowAccountEdit && tenantType == 1">{{$t('common.base.resetPwd')}}</div></el-dropdown-item>
                        </el-dropdown-menu>
                      </el-dropdown>
                      
                      <div v-else>
                      <el-button
                        :disabled="scope.row.pending"
                        type="text"
                        @click="openCreateUserPanel(scope.row)"
                        v-if="allowAccountEdit"
                      >{{$t('common.base.edit')}}</el-button
                      >
                      <el-button
                        :disabled="scope.row.pending"
                        v-if="scope.row.enabled == 1 && allowAccountStop"
                        type="text"
                        style="color: #e6a23c"
                        @click="toggleEnable(scope.row)"
                      >{{$t('common.base.deactivate')}}</el-button
                      >
                      <el-button
                        :disabled="scope.row.pending"
                        v-else-if="allowAccountStop"
                        type="text"
                        @click="toggleEnable(scope.row)"
                      >{{$t('common.base.enable')}}</el-button
                      >
                      <el-button
                        :disabled="scope.row.pending"
                        type="text"
                        style="color: #fb602c"
                        @click="deleteDeptUser(scope.row)"
                        v-if="allowAccountDelete"
                      >{{$t('common.base.delete')}}</el-button
                      >
                      <el-button
                        type="text"
                        @click="userResetPwdConfirm(scope.row.userId)"
                        v-if="allowAccountEdit && tenantType == 1"
                      >{{$t('common.base.resetPwd')}}</el-button
                      >
                      </div>
                      <!-- <el-button
                        type="text"
                        style="color: #fb602c"
                        @click="openChangeDialog(scope.row)"
                        v-if="allowAccountEdit"
                      >资质管理</el-button
                      > -->
                    </template>
                  </el-table-column>
                </el-table>


              </div>


            </div>
            <!-- end 部门人员 -->
            <div class="table-footer bbx-normal-table-footer">
              <div class="list-info">
                <i18n path="common.base.table.totalCount">
                  <span place="count" class="level-padding">{{userPage.total}}</span>
                </i18n>
                <template v-if="multipleSelection && multipleSelection.length">
                  <i18n path="common.base.table.selectedNth">
                    <span place="count" class="product-selected-count">{{multipleSelection.length}}</span>
                  </i18n>
                  <span class="product-selected-count" @click="selectionToggle()">{{$t('common.base.clear')}}</span>
                </template>
              </div>
              <el-pagination
                class="customer-table-pagination"
                :pager-count="tenantType==0?5:7"
                background
                @current-change="jump"
                @size-change="handleSizeChange"
                :page-sizes="defaultTableData.defaultPageSizes"
                :page-size="params.pageSize"
                :current-page="params.pageNum"
                layout="prev, pager, next, sizes, jumper"
                :total="userPage.total"
              ></el-pagination>
            </div>
          </el-tab-pane>
          <el-tab-pane :label="$t('common.label.subDepartment_1')" name="dept">
            <!-- start 下级部门 -->
            <div class="department-child-block">
              <!-- start 下级部门列表 -->

              <template v-if="subDeptExpand">
                <div class="dept-search-group">
                  <div class="dept-search-group-left">
                    <el-input
                      v-model="subDeptKeyword"
                      :placeholder="$t('department.label.screenChildMember')"
                      style="width: 200px;margin-right:12px"
                      @change="subDeptSearch"
                    >
                      <!-- @input="subDeptSearch"
                      @keyup.enter.native="subDeptSearch" -->
                      <i slot="prefix" class="el-input__icon el-icon-search"></i>
                    </el-input>
                    <base-button
                      type="primary"
                      @event="addDepartment()"
                      id="v-dept-step-3"
                      v-if="allowTagCreate"
                      v-track="$track.formatParams('CREATE_DEPT')"
                    ><i class="iconfont icon-add2" style="margin-right:6px" ></i>{{$t('common.label.addSubDepartment')}}</base-button
                    >
                  </div>
                </div>
                <div class="department-user-table" v-loading="deptLoading">
                  <el-table
                    v-table-style
                    border
                    class="team-table bbx-normal-list-box"
                    :data="dept.list"
                    stripe
                    @header-dragend="headerDragend"
                    :height="tableContainerHeight"
                    header-row-class-name="common-list-table-header__v2"
                  >
                    <template slot="empty">
                      <BaseListForNoData
                        v-show="!deptLoading && !dept.list.length"
                        :notice-msg="$t('department.label.noChildDepartment')"
                      ></BaseListForNoData>
                    </template>

                    <el-table-column
                      :label="$t('common.label.departmentName')"
                      :width="tableListForWidthStashdept.tagName.width"
                      show-overflow-tooltip>
                      <template slot-scope="scope">
                        <template v-if="tenantType == 2 && scope.row.dingId">
                          <open-data type="departmentName" :openid="scope.row.dingId"></open-data>
                        </template>
                        <template v-else>
                          {{scope.row.tagName}}
                        </template>
                      </template>
                    </el-table-column>
                    <el-table-column :label="$t('common.label.departmentLeader')" :width="tableListForWidthStashdept.depLeader.width" show-overflow-tooltip>
                      <template slot-scope="scope" v-if="scope.row.teamLeaders">
                        <template v-if="tenantType == 2">
                          <open-data v-for="item in scope.row.teamLeaders" :key="item.staffId" type="userName" :openid="item.staffId"></open-data>
                        </template>
                        <template v-else>
                          {{scope.row.teamLeaders.map(i => (i && i.displayName) || '').join('，')}}
                        </template>
                      </template>
                    </el-table-column>
                    <el-table-column prop="phone" :width="tableListForWidthStashdept.phone.width" :label="$t('common.base.phone')" show-overflow-tooltip />
                    <el-table-column prop="depPosition" :label="$t('common.label.departmentLocation')" :width="tableListForWidthStashdept.depPosition.width" show-overflow-tooltip>
                      <template slot-scope="scope">
                         {{ scope.row | fmt_address }}
                      </template>
                    </el-table-column>
                    <el-table-column prop="manageArea" :label="$t('common.label.principalLocation')" :width="tableListForWidthStashdept.manageArea.width" show-overflow-tooltip>
                      <template
                        slot-scope="scope"
                        v-if="scope.row.tagPlaceList"
                      >{{
                        scope.row.tagPlaceList
                          .map( p => fmtDist(p) )
                          .join('，\n')
                      }}</template
                      >
                    </el-table-column>

                    <el-table-column prop="workArea" :label="$t('common.base.operation')" width="120px" fixed="right">
                      <template slot-scope="scope">
                        <el-dropdown class="dropdown" v-if="allowTagEdit && allowTagDelete">
                          <span class="cur-point">
                            {{$t('common.base.more')}}<i class="el-icon-arrow-down el-icon--right"></i>
                          </span>
                          <el-dropdown-menu slot="dropdown" class="lang-select-dropdown">
                            <el-dropdown-item><div @click="openDepartmentEditPanel(scope.row)" v-if="allowTagEdit">{{$t('common.base.edit')}}</div></el-dropdown-item>
                            <el-dropdown-item><div @click="delDepartment(scope.row.id)" v-if="allowTagDelete">{{$t('common.base.delete')}}</div></el-dropdown-item>
                          </el-dropdown-menu>
                        </el-dropdown>
                        <div v-else>
                        <el-button
                          type="text"
                          @click="openDepartmentEditPanel(scope.row)"
                          v-if="allowTagEdit"
                        >{{$t('common.base.edit')}}</el-button
                        >
                        <el-button
                          type="text"
                          style="color: #fb602c"
                          @click="delDepartment(scope.row.id)"
                          v-if="allowTagDelete"
                        >{{$t('common.base.delete')}}</el-button
                        >
                        </div>
                      </template>
                    </el-table-column>
                  </el-table>

                  <div class="table-footer bbx-normal-table-footer">
                    <div class="list-info">
                      <i18n path="common.base.table.totalCount">
                        <span place="count" class="level-padding">{{ dept.total }}</span>
                      </i18n>
                    </div>
                    <el-pagination
                      class="customer-table-pagination"
                      background
                      :pager-count="tenantType==0?5:7"
                      @current-change="deptjump"
                      @size-change="depthandleSizeChange"
                      :page-sizes="defaultTableData.defaultPageSizes"
                      :page-size="dept.pageSize"
                      :current-page="dept.pageNum"
                      layout="prev, pager, next, sizes, jumper"
                      :total="dept.total"
                    ></el-pagination>
                  </div>
                </div>

              </template>
              <!-- end 下级部门列表 -->

              <!-- <div class="no-data-block" v-else>
            当前部门不包含下级部门 <span class="active-btn" @click="addDepartment">添加子部门</span>
          </div>-->
            </div>
            <!-- end 下级部门 -->
          </el-tab-pane>
          <el-tab-pane :label="$t('department.label.managerServiceProvider')" name="provider" v-if="isProviderManager">
            <service-provider-tab
              ref="providerRef"
              :tenant-type="tenantType"
              :table-list-for-width-stashprovider="tableListForWidthStashprovider"
              @service-header-dragend="headerDragend"
            ></service-provider-tab>
          </el-tab-pane>
        </el-tabs>
      </div>
      <!-- end 右侧子部门 人员列表 -->
    </div>
    <!-- end 主要内容 -->

    <!-- start 新建/编辑 部门 面板 @deprecated 已废弃 -->
    <department-edit-panel
      ref="departmentEditPanel"
      @create="departmentCreate"
      @edit="departmentEdit"
      @delete="departmentDelete"
    ></department-edit-panel>
    <!-- end 新建/编辑 部门 面板 -->

    <!-- start 新建账号 -->
    <base-modal
      :show.sync="userDialogVisible"
      class="add-dialog-container service_body" width="720px" @closed="handleUserDialogClose"
      :title="dialogUserTitle"
    >
      <create-user-panel
        v-if="createUserPanelVisible"
        ref="createUserPanel"
        @submit="userAdd"
        :user-row="userRow"
        :account-info="internalAccountInfo"
        key-from='dept'
      ></create-user-panel>
      <span slot="footer" class="dialog-footer" style="width:100%">
        <div class="flex-x">
          <div class="flex-1 overHideCon-1">
            <template v-if="haveUserNote">
              <el-checkbox v-model="createNeedNote">{{$t('department.label.label5')}}</el-checkbox>
              <el-tooltip class="item" effect="dark" :content="$t('department.label.tips1')" placement="bottom">
                <i class="iconfont icon-question-circle mar-l-5 font-15-i"></i>
              </el-tooltip>
              </template>
            
          </div>
          <div>
            <el-button @click="userDialogVisible = false">{{$t('common.base.cancel')}}</el-button>
          <el-button type="primary" @click="userDialogSubmit"
          >{{$t('common.base.confirm')}}</el-button
          ></div>
          
        </div>
      </span>
    </base-modal>
    <!-- end 新建账号 -->

    <!-- 自动分配角色的对话框 -->
    <el-dialog
      :title="$t('department.label.autoAssiAccount')"
      :visible.sync="roleDialogVisible"
      width="35%"
      @close="roleDialogClosed"
    >
      <el-form label-position="top" :model="roleForm" ref="roleFormRef">
        <el-form-item
          :label="$t('department.label.defaultRole')"
        ></el-form-item>
        <el-select
          v-model="roleForm.roleId"
          :placeholder="$t('department.label.selectUser')"
          style="width: 100%"
        >
          <el-option
            v-for="item in autoAuthRoles"
            :label="item.text"
            :value="item.id"
            :key="item.id"
          ></el-option>
        </el-select>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="roleDialogVisible = false">{{ $t('common.base.cancel') }}</el-button>
        <el-button
          type="primary"
          :disabled="pending"
          :loading="pending"
          @click="dispatchRole"
        >{{ $t('common.base.confirm') }}</el-button
        >
      </span>
    </el-dialog>

    <!-- 导出动态的对话框 -->
    <el-dialog
      :title="$t('department.exportStatus.title')"
      :visible.sync="exportDialogvisible"
      width="600px"
      @close="exportDialogClosed"
    >
      <el-form label-position="top" ref="exportFormRef" >
        <el-form-item :label="$t('department.exportStatus.selectTime')">
          <el-date-picker
            v-model="selectdatetime"
            type="daterange"
            align="right"
            unlink-panels
            :range-separator="$t('common.base.to')"
            :start-placeholder="$t('common.base.startDate')"
            :end-placeholder="$t('common.base.endDate')"
            :default-time="['00:00:00', '23:59:59']"
            value-format="timestamp"
            :picker-options="pickerOptions"
          ></el-date-picker>
        </el-form-item>
        <el-form-item :label="$t('department.exportStatus.statusType')" >
          <el-checkbox v-model="checkedAllTypes">{{$t('department.exportStatus.workStatus')}}</el-checkbox>
          <el-checkbox-group v-model="activeTypes" :disabled="checkedAllTypes">
            <el-checkbox :label="item.value" v-for="item in dynamicTypes" :key="item.value">{{item.name}}</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="exportDialogClosed">{{$t('common.base.cancel')}}</el-button>
        <el-button
          type="primary"
          :disabled="pending"
          :loading="pending"
          @click="exportData"
        >{{ pending ? $t('common.base.exporting') : $t('common.base.export') }}</el-button
        >
      </span>
    </el-dialog>

    <!-- 重置密码的对话框 -->
    <el-dialog
      :title="$t('common.base.resetPwd')"
      :visible.sync="resetDialogvisible"
      width="400px"
      @close="resetDialogClosed"
      class="reset-dialog-form-dialog"
    >
      <el-form
        label-position="top"
        ref="restFormRef"

        class="reset-dialog-form"
        :rules="changePassWordFormRules"
        :model="resetForm"
      >
        <label>{{$t('department.resetPassword.title')}}</label>
        <el-form-item :label="`${$t('department.resetPassword.newPassword')}：`" required prop="pwd">
          <input type="password" style="position: fixed; left: -9999px" />
          <el-input
            :placeholder="$t('department.resetPassword.inputPassword')"
            v-model="resetForm.pwd"
            type="password"
            show-password
            autocomplete="off"
          ></el-input>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="resetDialogClosed">{{$t('common.base.cancel')}}</el-button>
        <el-button
          type="primary"
          :disabled="pending"
          :loading="pending"
          @click="resetUserPwd"
        >{{$t('common.base.confirm')}}</el-button
        >
      </span>
    </el-dialog>

    <!--start 编辑账号名称 -->
    <modifyname-dialog
      ref="ModifyNameToast"
      @handleClose="handleClose"
      v-if="showModifynameDialog"
      @refresh="refresh"
    ></modifyname-dialog>
    <!--end 编辑账号名称 -->

    <!-- tour start -->
    <v-tour
      name="myTour"
      :steps="deptSteps"
      :options="deptOptions"
      :callbacks="myCallbacks"
    >
      <template slot-scope="tour">
        <transition name="fade">
          <template v-for="(step, index) of tour.steps">
            <v-step
              v-if="tour.currentStep === index"
              :key="index"
              :step="step"
              :previous-step="tour.previousStep"
              :next-step="tour.nextStep"
              :stop="tour.stop"
              :is-first="tour.isFirst"
              :is-last="tour.isLast"
              :labels="tour.labels"
            >
              <template>
                <div slot="content" class="tour-content-box">
                  <div class="tour-left-tips">
                    {{ `${index + 1}/${deptSteps.length}` }}
                  </div>
                  <div class="tour-content">
                    <div class="flex-x tour-content-head">
                      {{ deptSteps[index].title }}
                    </div>
                    <div class="tour-content-con">
                      {{ deptSteps[index].content }}
                    </div>
                  </div>
                </div>
                <div slot="actions" class="tour-bottom">
                  <!-- <div class="text" v-if="index > 0" @click="tour.previousStep">
                    上一步
                  </div> -->
                  <div
                    class="btns"
                    v-if="index < deptSteps.length - 1"
                    @click="tour.nextStep"
                  >
                    {{$t('common.base.nextStep')}}
                  </div>
                  <div
                    v-if="index == deptSteps.length - 1"
                    class="btns"
                    @click="tour.stop"
                  >
                    {{$t('department.myTour.konwlege')}}
                  </div>
                </div>
              </template>
            </v-step>
          </template>
        </transition>
      </template>
    </v-tour>
    <!-- tour end -->

    <el-dialog
      :visible.sync="guideDialogVisible"
      width="300px"
      top="38vh"
      :show-close="false"
    >
      <span>{{$t('department.myTour.updateOver')}}</span>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="handleGuideClose"
        >{{$t('common.base.confirm')}}</el-button
        >
      </span>
    </el-dialog>
    <!-- 添加部门 start -->
    <base-modal :title="dialogTitle" :show.sync="deptDialogVisible" class="add-dialog-container service_body" width="700px" @closed="handleDeptDialogClose">
      <team-edit-view
        ref="team"
        v-if="teamEditViewVisible"
        @deptSubmit="submitAddDept"
        :selected-dept="selectedDept"
        :type-service-provider="0"
        :show-parent="showParent"
        :id="deptEditId"
      ></team-edit-view>
      <span slot="footer" class="dialog-footer">
        <el-button @click="cancelCreateDept">{{$t('common.base.cancel')}}</el-button>
        <el-button type="primary" @click="submit">{{$t('common.base.confirm')}}</el-button>
      </span>
    </base-modal>
    <!-- 添加部门 start -->
    <!-- start 导入服务微信 -->
    <base-import
      :title="$t('department.serviceWxModal.title')"
      ref="serviceWxModal"
      :is-import-now="true"
      @success="importServiceSuccess"
      :v-text="importWechat"
    >
      <div slot="tip">
        <div class="base-import-warn">
          <i18n path="common.base.importModal.downloadTemplateTip" tag="span">
            <a place="link" :href="`${importWechatTem}?tagId=${selectedDept.id}`">{{$t('common.base.importModal.importTemplate')}}</a>
          </i18n>
          <br />
          {{$t('department.serviceWxModal.tip[0]')}}
          <br />
          {{$t('department.serviceWxModal.tip[1]')}}
          <br />
          {{$t('department.serviceWxModal.tip[2]')}}
        </div>
      </div>
    </base-import>
    <!-- end 导入服务微信 -->

    <!-- start 导入服务电话 -->
    <base-import
      :title="$t('department.serviceTelModal.title')"
      ref="serviceTelModal"
      :is-import-now="true"
      @success="importServiceSuccess"
      :action="importCellPhone"
    >
      <div slot="tip">
        <div class="base-import-warn">
          <i18n path="common.base.importModal.downloadTemplateTip" tag="span">
            <a place="link" :href="`${importCellPhoneTem}?tagId=${selectedDept.id}`">{{$t('common.base.importModal.importTemplate')}}</a>
          </i18n>
          <br />
          {{$t('department.serviceTelModal.tip[0]')}}
          <br />
          {{$t('department.serviceTelModal.tip[1]')}}
          <br />
          {{$t('department.serviceTelModal.tip[2]')}}
          <br />
          {{$t('department.serviceTelModal.tip[3]')}}
          <br />
          {{$t('department.serviceTelModal.tip[4]')}}
        </div>
      </div>
    </base-import>
    <!-- end 导入服务电话 -->
    <!-- start 导入企业微信通讯录 -->
    <base-import
      :title="$t('department.wechatContact.title')"
      ref="wechatContactRef"
      @success="importWechatContact"
      :action="wechatContactImport"
    >
      <div slot="tip">
        <div class="base-import-warn">
          {{$t('department.wechatContact.tip[0]')}}
          <br />
          {{$t('department.wechatContact.tip[1]')}}
          <br />
          {{$t('department.wechatContact.tip[2]')}}
        </div>
      </div>
    </base-import>
    <!-- end 导入企业微信通讯录 -->

    <!-- 高级搜索框 -->
    <base-search-drawer
      :show.sync="visible"
      :storage-key="advancedColumnNumStorageKey"
      @reset="resetParams"
      @search="search(true)"
      @changeWidth="setAdvanceSearchColumn"
      @getColumnNum="setAdvanceSearchColumn"
    >
      <base-search-panel ref="searchPanel" :column-num="columnNum" :fields="fields">
      </base-search-panel>
    </base-search-drawer>


    <!-- start 导入账号 -->
    <base-import
      :title="$t('department.accountModal.title')"
      ref="accountModal"
      :is-import-now="false"
      @success="accountSuccess"
      :action="importAccount"
    >
      <div slot="tip">
        <div class="base-import-warn">
          <i18n path="common.base.importModal.downloadTemplateTip" tag="span">
            <a place="link" :href="`${importAccountUrl}`">{{$t('common.base.importModal.importTemplate')}}</a>
          </i18n>
          <br />
          {{$t('department.accountModal.tip[0]')}}
          <br />
          {{$t('department.accountModal.tip[1]')}}
          <br />
          {{$t('department.accountModal.tip[2]')}}
          <br />
          {{$t('department.accountModal.tip[3]')}}
          <br />
          {{$t('department.accountModal.tip[4]')}}
          <br />
          {{$t('department.accountModal.tip[5]')}}
          <br />
          {{ importRoleTip }}
          <br />
          {{$t('department.accountModal.tip[7]')}}
          <br />
          {{$t('department.accountModal.tip[8]')}}
          <br />
          {{$t('department.accountModal.tip[9]')}}
          <br />
          {{$t('department.accountModal.tip[10]')}}
        </div>
      </div>
    </base-import>
    <!-- end 导入账号 -->

    <!-- start 批量更新 -->
    <base-import
      :title="$t('common.base.batchUpdate')"
      ref="updateModal"
      :is-import-now="false"
      @success="accountSuccess"
      :action="updateAccount"
    >
      <div slot="tip">
        <div class="base-import-warn">
          <i18n path="common.base.importModal.downloadTemplateTip" tag="span">
            <a place="link" @click="downloadTem" href="javascript:;">{{$t('common.base.importModal.importTemplate')}}</a>
          </i18n>
        </div>
      </div>
    </base-import>
    <!-- end 批量更新 -->
    <base-export
      ref="exportPanel"
      :alert="exportAlert"
      :columns="exportColumns"
      :validate="checkExportCount"
      :isUserListFlag='isUserListFlag'
      @goExport="goExport"
    />
    <div ref="bridge" style="display: none;"></div>
    <change-dialog ref="changeDialog" :row='currentRow'></change-dialog>

  </div>
  <!-- end 选择组织架构页面 -->
</template>

<script>
// pageDes 组织架构管理
/* api */
import {
  getRoleUser,
  getDelUser,
  autoAuth,
  addRoleUser,
  delRoleUser,
  resetPwdUpdateAdmin,
  getDepartmentUserCount,
  addDepartment,
  updateDepartment,
  deleteDepartment,
  updateDepartmentUserBatch,
  getBuyAndUseUserNum,
  createAndAddDepartmentUser,
  getChildTagList,
  getBaseLabelList
} from '@src/api/DepartmentApi';

import * as UserCenterApi from '@src/api/UserCenterApi';
import * as TeamApi from '@src/api/TeamApi';
import { getRoleTree } from '@src/api/serviceProviderApi';

import md5 from 'js-md5';
import { getAdvancedFields } from './fields';
import { safeNewDate } from '@src/util/time';

/* enum */
import StorageKeyEnum from '@model/enum/StorageKeyEnum.ts'

import { isAllotByDepartment, isOpenData } from '@src/util/platform'
import {checkButtonDisplayed, getRootWindow} from '@src/util/dom';
/* components */
import CreateUserPanel from '@src/modules/dept/component/CreateUserPanel.vue';
import DepartmentEditPanel from '@src/modules/dept/component/DepartmentEditPanel.vue';
import ModifyName from '@src/modules/dept/component/ModifyName';
import ServiceProviderTab from '@src/modules/dept/component/ServiceProviderTab';
import {
  isBasicEditionControl,
  isBasicEditionHideEvent,
  isBasicEditionHidePart
} from '@shb-lib/version';
import TeamEditView from '@src/modules/dept/component/TeamEditView.vue';
import BaseSearchDrawer from 'packages/BaseSearchDrawer';
import BaseSearchPanel from 'packages/BaseSearchPanel';

// const
import { RoleType, TagType } from '@src/modules/dept/AdvancedType.ts';
import ChangeDialog from '@src/modules/serviceProvider/component/ChangeDialog.vue';

/* utils */
import _ from 'lodash';
import http from '@src/util/http';
import Page from '@model/Page';
import Platform from '@src/util/platform.ts';
import tourGuide from '@src/mixins/tourGuide';
import { storageGet, storageSet } from '@src/util/storage';
import { getRootWindowInitData, setRootWindowInitData } from '@src/util/window'
let rootWindowInitDataData = getRootWindowInitData()
/* export & import */
import { importWechat, importWechatTem, importCellPhone, importCellPhoneTem, wechatContactImport, importAccount, importAccountTem, updateAccount, importAccountTemCSCAndBSC } from '@src/api/Import';

import { storageGet as storageGetLocal, storageSet as storageSetLocal} from '@src/util/storageV2.js'
import { useRole } from '@hooks/useRole.ts'

import { ValidatePassWordReg } from '@src/model/const/Reg'
import { PASS_WORD_MESSAGE } from '@src/model/const/Alert'

import AuthMixin from '@src/mixins/authMixin'
import { formatDate, randomString, objectToUrlParams } from 'pub-bbx-utils';
import { PageRoutesTypeEnum } from 'pub-bbx-global/pageType/dist/enum/PageRoutesEnum'
import { BaseSelectUserModeEnum } from '@src/component/common/BaseSelectUser'
import { fmtDist } from '@src/util/addressUtil';
import { defaultTableData } from '@src/util/table'

import addressKeyToViewLanguage, { getCountryKey } from '@src/component/common/BaseAddressSwitch/addressNameMultiLanguage';
/* util */
import { getProductLineRoleNames } from '@shb-lib/tenant'
/* tenant */
import { isCustomerServiceCloudProductAndBusinessServiceCloudProduct } from '@shb-lib/tenant'
/* mixin */
import { VersionControlTaskMixin, VersionControlSparePartMixin, VersionControlOtherMixin } from '@src/mixins/versionControlMixin'

const DEPT_GUIDE = 'dept_guide',
  DEPT_GUIDE_DIALOG = 'dept_guide_dialog';
let export_state;
const pageSizeStorageKey = 'dept_depart_list';

import LoginUserBan from '@src/modules/dept/component/loginUserBan.vue'
import { useStateNoteUserSendMessage } from '@src/modules/dept/mock.ts'

const { findThisStatus, findThisStatusDes, findThisStatusClass, findThisStatusShowNote, noteItem, haveUserNote } = useStateNoteUserSendMessage()

let validatePass = (rule, value, callback) => {

  if (!value) {
    callback(new Error(this.$t('common.base.inputPassword')));
  } else {

    if (value) {
      if (ValidatePassWordReg.test(value)) {
        callback();
      } else {
        callback(new Error(PASS_WORD_MESSAGE));
      }
    }

    callback();
  }
};
import { formatAddress } from 'pub-bbx-utils';
export default {
  name: 'department-view',
  inject: ['initData'],
  mixins: [
    tourGuide,
    AuthMixin,
    VersionControlTaskMixin,
    VersionControlSparePartMixin,
    VersionControlOtherMixin,
  ],
  data() {
    return {
      isUserListFlag:true,
      type:'',
      exportColumns:[
        {displayName:this.$t('common.label.name'),label:this.$t('common.label.name'),export:true,field: "displayName",fieldName: "displayName",formType: "text"},
        {displayName:this.$t('common.fields.employeeNumber.displayName'),label:this.$t('common.fields.employeeNumber.displayName'),export:true,field: "workNo",fieldName: "workNo",formType: "text"},
        {displayName:'UserID',label:'UserID',export:true,field: "userId",fieldName: "userId",formType: "text"},
        {displayName:this.$t('common.label.accountNumber'),label:this.$t('common.label.accountNumber'),export:true,field: "loginName",fieldName: "loginName",formType: "text"},
        {displayName:this.$t('common.label.ofDepartment'),label:this.$t('common.label.ofDepartment'),export:true,field: "tagName",fieldName: "tagName",formType: "text"},
        {displayName:this.$t('common.label.role'),label:this.$t('common.label.role'),export:true,field: "roles",fieldName: "roles",formType: "text"},
        {displayName:this.$t('common.label.phone'),label:this.$t('common.label.phone'),export:true,field: "cellPhone",fieldName: "cellPhone",formType: "text"},
        {displayName:this.$t('common.label.weChat'),label:this.$t('common.label.weChat'),export:true,field: "wechat",fieldName: "wechat",formType: "text"},
        {displayName:this.$t('common.label.email'),label:this.$t('common.label.email'),export:true,field: "email",fieldName: "email",formType: "text"},
        {displayName:this.$t('common.label.status'),label:this.$t('common.label.status'),export:true,field: "status",fieldName: "status",formType: "text"}
      ],
      defaultTableData,
      internalAccountInfo: {}, //国际化账号信息
      isOpenData,
      isButtonDisplayed: checkButtonDisplayed(),
      createUserPanelVisible: false,
      userDialogVisible: false,
      deptDialogVisible: false,
      showParent: false,
      subDeptExpand: true,
      subDeptKeyword: '',
      guideDialogVisible: false,
      isAllotByDept: false,
      nowGuideStep: 5,
      collapse: false,
      collapseLeft: true,
      collapseRight: false,
      showModifynameDialog: false,
      deptKeyword: '',
      activeName: 'tag',
      activeName1: 'user',
      // dept_role_data: [],
      roles: [],
      selectedRole: {},
      keyword: '',
      roleKeyword: '',
      roleLoading: false,
      roleDialogVisible: false,
      pending: false,
      autoAuthRoles: [],
      roleForm: {
        roleId: '0'
      },
      teamEditViewVisible: false,
      roleMultipleSelection: [],
      roleParams: {},
      exportDialogvisible: false,
      resetDialogvisible: false,
      resetForm: {
        userId: '',
        pwd: ''
      },

      selectdatetime: [],
      pickerOptions: {
        shortcuts: [
          {
            text: this.$t('common.time.lastWeek'),
            onClick(picker) {
              const end = safeNewDate();
              const start = safeNewDate();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit('pick', [start, end]);
            }
          },
          {
            text: this.$t('common.time.lastMonth'),
            onClick(picker) {
              const end = safeNewDate();
              const start = safeNewDate();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit('pick', [start, end]);
            }
          },
          {
            text: this.$t('common.time.lastThreeMonth'),
            onClick(picker) {
              const end = safeNewDate();
              const start = safeNewDate();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit('pick', [start, end]);
            }
          },
          {
            text: this.$t('common.time.lastHalfYear'),
            onClick(picker) {
              const end = safeNewDate();
              const start = safeNewDate();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 180);
              picker.$emit('pick', [start, end]);
            }
          },
          {
            text: this.$t('common.time.lastYear'),
            onClick(picker) {
              const end = safeNewDate();
              const start = safeNewDate();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 360);
              picker.$emit('pick', [start, end]);
            }
          }
        ]
      },
      deptInfo: {},
      userRow: '',
      allowCheckDept: false,
      depts: [],
      allDepts: [], //所有部门数据
      deptUserCount: {}, // 部门人员数量统计
      isSeeAllOrg: false, // 是否开始降低组织架构人员可见性开关
      isNickname: !!rootWindowInitDataData.IS_WECHAT_NAME, // 是否显示企业微信昵称 1显示企业微信昵称, 0不显示
      loading: false,
      userLoading: true,
      deptLoading: false,
      multipleSelection: [],
      params: {},
      selectedDept: {}, // 选中的部门
      userPage: new Page(), // 用户列表
      rolePage: new Page(),
      dept: new Page(),
      synchronousState: false, // 同步状态
      subDepartments: [], // 子部门
      subDepartmentsPage: new Page(),
      userCount: 0, // 已开通账号数量
      accountNum: 0, // 账号总数量
      surplusNum: 0, // 剩余
      deptEditId: '',
      currentTabId: '',
      visible: false,
      columns: [],
      columnNum: 1,
      advancedColumnNumStorageKey: StorageKeyEnum.DeptListAdvancedColumnNum,
      rolesList: [],
      baseLaberlList: [],
      importWechat,
      importWechatTem,
      importCellPhone,
      importCellPhoneTem,
      wechatContactImport,
      // 存储列表宽度缓存
      tableListForWidthStashuser:{
        workNo:{width:'120px'},
        displayName:{width:'180px'},
        loginName:{width:'120px'},
        roleDepartment:{width:'120px'},
        role:{width:'120px'},
        cellPhone:{width:'120px'},
        wechat:{width:'120px'},
        email:{width:'120px'},
        enabled:{width:'120px'},
        createTime:{width:'160px'},
        workArea:{width:'215px'},
        loginStatus:{width:'200px'},
      },
      tableListForWidthStashdept:{
        tagName:{},
        depLeader:{},
        phone:{},
        depPosition:{},
        manageArea:{},
        workArea:{width:'215px'}
      },
      // 服务商的宽度
      tableListForWidthStashprovider: {
        providerCode: {},
        providerName: {},
        contacts: {},
        providerPhone: {},
        providerType:{},
        workArea: { width:'215px'}
      },
      // 列表缓存标识
      tableStashKey:'departmentList',
      isSystemManager: useRole().isSystemManager,
      importAccountTem,
      importAccountTemCSCAndBSC,
      importAccount,
      updateAccount,
      dynamicTypes:[
        {value:0, name:this.$t('common.base.taskRemark')},
        {value:1, name:this.$t('common.base.taskLog')},
        {value:2, name:this.$t('common.base.taskPosition')}
      ],
      activeTypes:[],
      checkedAllTypes:true,
      currentRow:{},
      changePassWordFormRules: {
        pwd: [
          {
            required: true,
            validator: validatePass,
            trigger: ['blur', 'change']
          },
          { min: 8, message: this.$t('department.formRules.pwd'), trigger: 'blur' }
        ],
      },
      tableContainerHeight:'440px',
      delTableContainerHeight: '440px',
      moreDropDownComponentKey: randomString(),
      // 部门位置翻译后的国家省市区字段集合
      deptSiteAddressNameObj:{},
      departmentUserTableKey: randomString(),
      createNeedNote:true,
      haveUserNote,
    };
  },
  watch:{
    activeName1(newVal, oldVal){
      this.$nextTick(()=>{
        this.buildColumn()
      })
    },
    checkedAllTypes(newVal){
      if(newVal)this.activeTypes = []
    }
  },
  computed: {
    isShowTask() {
      return this._isShowTaskModule
    },
    hideOtherUserContent() {
      return (
        this.isShowTask
        ? this.$t('department.organizational.mainContent.hidenOtherUserContent')
        : this.$t('department.organizational.mainContent.hideOtherUserContentCSC')
      )
    },
    needDropdownTwo() {
      return this.allowAccountEdit ? (this.allowAccountStop || this.allowAccountDelete) : (this.allowAccountStop && this.allowAccountDelete)
    },
    needDropdownOne() {
      return this.allowAccountEdit || this.allowAccountStop || this.allowAccountDelete
    },
    isWhiteList() {
      return rootWindowInitDataData?.WHITE_LIST
    },
    dialogTitle(){
      return this.deptEditId ? this.$t('department.formTitle.modifyDepartment') : this.$t('department.formTitle.createDepartment')
    },
    dialogUserTitle(){
      return this.userRow ? this.$t('department.formTitle.modifyAccount') : this.$t('department.formTitle.createAccount')
    },
    corpId() {
      return this.initData.corpId || '';
    },
    // 0：钉钉端，1：自建，2：企微端 4：飞书
    tenantType() {
      return this.initData.tenantType;
    },
    authorities() {
      return this.initData.authorities || {};
    },
    allowTagCreate() {
      return this.authorities?.AUTH_TAG
    },
    allowTagEdit() {
      return this.authorities?.TAG_EDIT
    },
    allowTagDelete() {
      return this.authorities?.TAG_DELETE
    },
    allowAccountCreate() {
      return this.authorities?.ACCOUNT_CREATE
    },
    allowAccountEdit() {
      return this.authorities?.AUTH_STAFF
    },
    allowAccountStop() {
      return this.authorities?.ACCOUNT_STOP
    },
    allowAccountDelete() {
      return this.authorities?.ACCOUNT_DELETE
    },
    allowAccountImport() {
      return this.authorities?.ACCOUNT_IMPORT && this.allowAccountCreate
    },
    allowAccountExport() {
      return this.authorities?.ACCOUNT_EXPORT
    },
    allowAddUser() {
      return (
        this.authorities.AUTH_STAFF == 3
        && this.authorities.AUTH_ROLE == 3
        && this.authorities.AUTH_TAG == 3
      );
    },
    // 查看组织架构权限对应之前的团队权限
    hasTagAuth() {
      // 多端默认true
      if (this.tenantType == 1) return true;
      return 'AUTH_TAG' in this.authorities;
    },
    // 账号权限
    hasStaffAuth() {
      // 多端默认true
      if (this.tenantType == 1) return true;
      return 'AUTH_STAFF' in this.authorities;
    },
    // 角色权限
    hasRoleAuth() {
      // 多端默认true
      if (this.tenantType == 1) return true;
      return 'AUTH_ROLE' in this.authorities;
    },
    // 是否账号管理权限
    isAuthStaff(){
      return 'AUTH_STAFF' in this.authorities;
    },
    showRoleDesc() {
      // 0  待分配账号
      // -1  已删除账号
      return this.selectedRole.id != 0 && this.selectedRole.id != -1;
    },
    isSystemRole() {
      // 系统内置角色id:1-10
      return this.selectedRole.id > 0 && this.selectedRole.id < 11;
    },
    canEditSystemRole() {
      // 系统管理员没有编辑和重置操作
      return this.selectedRole.id > 1 && this.selectedRole.id < 11;
    },
    isCustomeRole() {
      // 自定义角色id
      return this.selectedRole.id && this.selectedRole.id.length > 2;
    },
    roleDes() {
      if (this.selectedRole.id == 1)
        return this.$t('department.tips.managerNoModify');
      if (this.selectedRole.id >= 2 && this.selectedRole.id <= 10)
        return this.$t('department.tips.memberModify');
      if (this.isCustomeRole) return this.$t('department.tips.definedModify');
    },
    teamLeadersName() {
      return (
        this.deptInfo.teamLeaders
        && this.deptInfo.teamLeaders
          .map(i => (i && i.displayName) || '')
          .join('，')
      );
    },
    deptArea() {
      const tagPlaceList = this.deptInfo.tagPlaceList || [];
      if (!tagPlaceList.length) return '';
      let address = ''
      for(let p of tagPlaceList){
        address += `${formatAddress(p)}；`;
      }
      return address;
    },
    deptDescription() {
      const desc = this.deptInfo.description || '';
      return desc.length < 10 ? desc : `${desc.substring(0, 10)}...`;
    },
    canRemove() {
      // 主部门下面成员不能移除
      return this.selectedDept.parentId;
    },
    // 是否在钉钉环境
    isDingTalk() {
      return Platform.isDingTalk();
    },
    productV2Gray() {
      return this.initData.openSuperCodePro;
    },
    isBasicEditionControl() {
      return isBasicEditionControl();
    },
    // 基础版隐藏事件
    isBasicEditionHideEvent() {
      return isBasicEditionHideEvent();
    },
    // 基础版隐藏备件
    isBasicEditionHidePart() {
      return isBasicEditionHidePart();
    },
    dept_role_data() {
      let roles = this.initData.rolesJson;
      if (this.isBasicEditionControl && roles) {
        roles.forEach(item => {
          // 基础版普通管理员过滤信息管理
          if (item.id === '2') {
            let descStr = item?.desc;
            const flag = descStr.endsWith('等');
            if (flag) {
              descStr = descStr.substring(0, descStr.length - 1);
            }
            let descArr = descStr.split('、');
            descArr = descArr.filter(subItem => subItem !== '信息管理');
            item.desc = flag ? `${descArr.join('、')}等` : descArr.join('、');
          }
          // 基础版服务总监过滤信息管理、备件管理、费用管理
          if (item.id === '5') {
            let descStr = item?.desc;
            const flag = descStr.endsWith('等');
            if (flag) {
              descStr = descStr.substring(0, descStr.length - 1);
            }
            let descArr = descStr.split('、');
            descArr = descArr.filter(
              subItem =>
                subItem !== '信息管理'
                && subItem !== '备件管理'
                && subItem !== '费用管理'
            );
            item.desc = flag ? `${descArr.join('、')}等` : descArr.join('、');
          }
        });
      }

      return roles || [];
    },
    // 高级搜索字段
    fields() {
      let f = {};
      return getAdvancedFields(this)
        .map(field => {
          f = _.cloneDeep(field);
          let formType = f.formType;

          if (f.displayName === '所属部门') {
            formType = 'tags';
          }

          return Object.freeze({
            ...f,
            isNull: 1,
            formType,
            originalFormType: f.formType,
          })
        })
        .sort((a, b) => a.orderId - b.orderId)
        .filter( x => this.canRemove ? x.fieldName !== 'tags' : x );
    },
    // 是否开始服务商灰度
    isProviderManager() {
      const RootWindow = getRootWindow(window)
      return RootWindow.grayAuth?.providerManager || false
    },
    /**
     * @description 是否拥有 客服云产品和服务云产品
    */
    isCustomerServiceCloudProductAndBusinessServiceCloudProduct() {
      return isCustomerServiceCloudProductAndBusinessServiceCloudProduct()
    },
    importRoleTip() {
      return (
        this.isCustomerServiceCloudProductAndBusinessServiceCloudProduct
        ? this.$t('department.accountModal.cscAndBscTips[0]')
        : this.$t('department.accountModal.tip[6]')
      )
    },
    importAccountUrl() {
      return (
        this.isCustomerServiceCloudProductAndBusinessServiceCloudProduct
        ? this.importAccountTemCSCAndBSC
        : this.importAccountTem
      )
    }
  },
  mounted() {
    this.currentTabId = window.frameElement?.dataset?.id;

    // isAllotByDept对应钉钉或者企微飞书端是否按照通讯录选人 如果钉钉端之前勾选了按服务团队派单isAllotByDept为false,
    this.isAllotByDept = isAllotByDepartment()

    // 读取列表的分页缓存数据
    let pageSizeStash = storageGetLocal(pageSizeStorageKey) || '';
    pageSizeStash = pageSizeStash ? JSON.parse(pageSizeStash) : {};
    if(pageSizeStash.hasOwnProperty('user')){
      this.params['pageSize'] = pageSizeStash.user;
    }
    if(pageSizeStash.hasOwnProperty('dept')){
      this.dept['pageSize'] = pageSizeStash.dept;
    }

    this.buildColumn();

    this.initialize();

    this.$eventBus.$on('submit', this.userAdd)
    let that_ = this;
    // 监听切换后需要重新计算列表高度 后续可以用activated生命周期替换
    window.addEventListener('message', (event)=> {
      const {action, data} = event.data;
      if (action == 'shb.frame.activatedPage'){
        that_.$nextTick(()=> {
          that_.knowTableContainerHeight();
        })
      }
    });
  },
  methods: {
    findThisStatus, 
    findThisStatusDes, 
    findThisStatusClass,
    findThisStatusShowNote,
    noteItem,
    exportAlert(result, params = {}) {
      this.$platform.alert(result.message);
    },
    checkExportCount(ids, max) {
      let exportAll = !ids || ids.length == 0
      
      return (
        exportAll && this.userPage.total > max
          ? '为了保障响应速度，暂不支持超过5000条以上的数据导出，请您分段导出。'
          : null
      )
    },
    fmtDist,
    getProductLineRoleNames,
    async getInternalAccountInfo(params) {
      try {
        const { status, data= {} } = await UserCenterApi.getInternalAccountInfo(params)
        if(status == 0) {
          this.internalAccountInfo = data || {}
        }
      } catch (error) {
        console.warn('getInternalAccountInfo error', error)
      }
    }, 
    handleUserDialogClose() {
      this.createUserPanelVisible = false
    },
    handleDeptDialogClose() {
      this.teamEditViewVisible = false
    },
    openImportWechatContact(){
      this.$refs.wechatContactRef.open();
    },
    openChangeDialog(row){
      this.currentRow = row
      this.$refs.changeDialog.openDialog()
    },
    userDialogSubmit() {
      this.$refs.createUserPanel.validate();
    },
    addAdmin() {
      // this.$platform.openTab({
      //   id: 'dept_home',
      //   title: '部门主页',
      //   close: true,
      //   url: `/security/tag/home/${this.selectedDept.id}?parentTab=${this.currentTabId}`
      // });
      Platform.openAccurateTab({
        type: PageRoutesTypeEnum.PageDeptHome,
        key: this.selectedDept.id,
        params: `parentTab=${this.currentTabId}`,
      })
    },
    ChildTagList() {
      this.dept.tagName = this.subDeptKeyword;
      this.deptLoading = true

      this.dept.tagId = this.selectedDept.id;
      let { tagId, pageNum, pageSize, tagName } = this.dept;

      let res = getChildTagList({tagId, pageSize, pageNum, tagName });
      return res.then(deptList => {
        this.dept.merge(Page.as(deptList.data));
        this.dept.list = deptList.data?.list || [];
      })
      .finally(() => this.deptLoading = false)
    },
    submit() {
      this.$track.clickStat(this.$track.formatParams('CONFIRM_CREATE_DEPT', null, 'CREATE_DEPT_BTNS'));
      this.$refs.team.submit();
      this.dept.pageNum = 1;
    },
    cancelCreateDept() {
      this.$track.clickStat(this.$track.formatParams('CANCEL_CREATE_DEPT', null, 'CREATE_DEPT_BTNS'));
      this.deptDialogVisible = false;
    },
    submitAddDept(info) {
      // 更新主页内容
      this.$platform.refreshTab(PageRoutesTypeEnum.PageDeptHome);

      this.deptDialogVisible = false;
      this.teamEditViewVisible = false;
      // 父元素发生变化需要重载
      if(info.params?.id == this.selectedDept?.id && info.params?.parentId !== this.selectedDept?.parentId ) {
        return this.initialize(true);
      }
      this.initialize(false);
    },

    /* 打开服务电话弹出框 */
    openTelDialog() {
      this.$refs.serviceTelModal.open();
    },
    openWxDialog() {
      this.$refs.serviceWxModal.open();
    },
    /* 导入维护服务电话成功 */
    importServiceSuccess() {
      //
    },
    /* 导入企业微信通讯录成功 */
    importWechatContact() {
      // this.$message.success('上传成功');
    },
    openAccountModal(){
      this.$refs.accountModal.open();
    },
    /* 批量更新 */
    openUpdateModal(){
      this.$refs.updateModal.open();
    },
    /* 导入账号（独立端）成功 */
    accountSuccess() {
      this.$refs.multipleTable.clearSelection();
      this.multipleSelection = [];
    },
    subDeptSearch: _.debounce(function(e) {
      // 下级部门模糊搜索
      this.dept.pageNum = 1;
      this.ChildTagList();
    }, 500),
    handleGuideClose() {
      this.guideDialogVisible = false;
      storageSet(DEPT_GUIDE_DIALOG, 1);
      if (
        !storageGet(DEPT_GUIDE)
        || storageGet(DEPT_GUIDE) < this.deptSteps.length
      ) {
        this.$tours['myTour'].start();
        this.nowGuideStep = 0;
      }
    },
    btnCollapse(dir) {
      if (dir === 'left') {
        this.collapse = true;
        this.collapseLeft = !this.collapseLeft;
        this.collapseRight = true;
      } else {
        this.collapse = false;
        this.collapseRight = !this.collapseRight;
        this.collapseLeft = true;
      }
    },
    async refreshDept() {
      try {
        if (localStorage.getItem('dept-need-refresh') == 1) {
          // 刷新整个tab
          await this.initialize();
          localStorage.setItem('dept-need-refresh', 0);
        } else {
          // 只刷新当前部门信息
          await this.initDeptUser(_.cloneDeep(this.selectedDept));
        }
      } catch (error) {
        console.log(error);
      }
      return new Promise((resolve, reject) => {
        resolve();
      });
    },
    nextStep() {
      this.nowGuideStep++;
    },
    stopStep() {
      this.nowGuideStep = this.deptSteps.length;
      storageSet(DEPT_GUIDE, this.deptSteps.length);
    },
    handleClose() {
      this.showModifynameDialog = false;
    },
    refresh() {
      this.initialize(false);
    },
    // 同步企业微信通讯录
    async synchronousWeChat() {
      let timeout;
      try {
        this.synchronousState = true;
        // 获取token
        const token = await this.$http.get('/account/synToken');

        timeout = setTimeout(() => {
          this.$platform.alert(this.$t('department.tips.updateOnBackstage'));
          this.synchronousState = false;
        }, 30000);
        this.$http
          .get('/api/user/outside/all/syncAddressBook')
          .then(res => {
            this.synchronousState = false;

            timeout && clearTimeout(timeout);
            timeout = null;
            if (res.status == 0) {
              this.$platform.alert(this.$t('department.tips.updateSuccess'));
              window.location.reload();
            } else {
              this.$platform.alert( res.message || this.$t('department.tips.updateFailed'));
            }
          })
          .catch(err => {
            timeout && clearTimeout(timeout);
            timeout = null;
            this.synchronousState = false;
            console.error('toggleStatus catch err', err);
          });
      } catch (error) {
        timeout && clearTimeout(timeout);
        this.synchronousState = false;
        console.error(error);
      }
    },
    // 同步钉钉通讯录
    async syncDingTalkAddressBook() {
      let timeout;
      try {
        this.synchronousState = true;
        timeout = setTimeout(() => {
          this.$platform.alert(this.$t('department.tips.updateOnBackstage'));
          this.synchronousState = false;
        }, 30000);
        //  parent.httpGet("/dd/synAddressBook?corpId="+$("#corpId").val(),{},false,function(data){
        let res = await this.$http.get(
          `/api/user/outside/all/syncAddressBook`,
          {}
        );
        this.synchronousState = false;
        timeout && clearTimeout(timeout);
        timeout = null;
        if (res.status == 0) {
          this.$platform.alert(this.$t('department.tips.updateSuccess'));
          window.location.reload();
        } else {
          this.$platform.alert(res.message || this.$t('department.tips.updateFailed'));
        }
      } catch (error) {
        timeout && clearTimeout(timeout);
        this.synchronousState = false;
        console.error(error);
      }
    },
    // 同步飞书通讯录
    async synchronousFeiShu(){
      let timeout;
      try {
        this.synchronousState = true;
        timeout = setTimeout(() => {
          this.$platform.alert(this.$t('department.tips.updateOnBackstage'));
          this.synchronousState = false;
        }, 30000);
        //  parent.httpGet("/dd/synAddressBook?corpId="+$("#corpId").val(),{},false,function(data){
        let res = await this.$http.get(`/api/user/outside/all/syncAddressBook`,{});
        this.synchronousState = false;
        timeout && clearTimeout(timeout);
        timeout = null;
        if (res.status == 0) {
          this.$platform.alert(this.$t('department.tips.updateSuccess'));
          window.location.reload();
        } else {
          this.$platform.alert(res.message || this.$t('department.tips.updateFailed'));
        }
      } catch (error) {
        timeout && clearTimeout(timeout);
        this.synchronousState = false;
        console.error(error);
      }
    },

    debounceDept: _.debounce(async function() {
      // 部门模糊搜索
      try {
        this.depts = await this.fetchDept();
        this.initDeptUser(this.depts[0]);
      } catch (error) {
        console.log(error);
      }
    }, 1000),
    async toggleEnable(row) {
      const statusText = row.enabled ? this.$t('department.tips.enabledUser01') : this.$t('department.tips.enabledUser02');
      if (await this.$platform.confirm(statusText)) {
        row.pending = true;
        this.$http
        .post('/security/user/enable', { userId: row.userId }, false)
        .then(res => {
          row.pending = false;
          if (res.status) return this.$platform.alert(res.message);
          // this.initialize(false);
          this.fetchUser();
        })
        .catch(err => {
          row.pending = false;
          console.error('toggleStatus catch err', err);
        });
      }
    },
    async deleteDeptUser(row) {
      if (await this.$platform.confirm(this.$t('department.tips.deleteMember'))) {
        this.$http
          .post('/security/user/delete', { userId: row.userId }, false)
          .then(res => {
            if (res.status) return this.$platform.alert(res.message);
            this.initialize(false);
          })
          .catch(err => {
            row.pending = false;
            console.error('toggleStatus catch err', err);
          });
      }
    },
    openMap() {
      this.$fast.map
        .display(this.deptInfo.tagAddress, { title: this.$t('common.label.departmentLocation') })
        .catch(err => console.error('openMap catch an err: ', err));
    },
    // 导出动态
    exportFeed(type) {
      if (!type && !this.multipleSelection.length)
        return this.$platform.alert(this.$t('department.tips.pleaseSelectMember'));
      export_state = type;
      this.exportDialogvisible = true;
    },
    async goExport(checkedArr) {
      let isContinue = true
      if(this.isOpenData){
        isContinue = false
        await this.$confirm(this.$t('department.tips.exportAccountMessage'), this.$t('department.tips.exportTip'), {
          confirmButtonText: this.$t('common.base.export'),
          cancelButtonText: this.$t('common.base.cancel'),
          type: 'warning'
        }).then(()=>{
          isContinue = true
        }).catch(()=>{
          isContinue = false
        })
      }
      let date = formatDate(safeNewDate(), 'YYYY-MM-DD');
      let fileName = `${date}${this.$t('department.tips.memberMessage')}.xlsx`;
      if(isContinue){
        if (this.type === 'all') {
          // 导出全部
          // window.location.href = !this.selectedDept.parentId
          //   ? `/security/user/tag/exportBatch?type=0&checked=${checkedArr.join(',')}`
          //   : `/security/user/tag/exportBatch?tagId=${this.selectedDept.id}&type=0&checked=${checkedArr.join(',')}`;
          let url = !this.selectedDept.parentId ? `/security/user/tag/exportBatch?type=0&checked=${checkedArr.join(',')}`
            : `/security/user/tag/exportBatch?tagId=${this.selectedDept.id}&type=0&checked=${checkedArr.join(',')}`;
          this.$http.post(url, {}, true, {responseType: 'blob'})
          .then(blob => {
            let link = document.createElement('a');
            let url = URL.createObjectURL(blob);
            link.download = fileName;
            link.href = url;
            this.$refs.bridge.appendChild(link);
            link.click();
            setTimeout(() => {
              URL.revokeObjectURL(url);
              this.$refs.bridge.removeChild(link);
            }, 150);
          })
          .catch(err => console.error(err));
        } else {
          // 导出选中的
          let ids = [];
          for (const user of this.multipleSelection) {
            ids.push(user.userId);
          }
          // ids = ids.join(',');
          const params = {
            userIdList : ids,
            checked:checkedArr.join(',')
          }
          this.$http.post('/security/user/tag/exportBatch/new', params, true, {responseType: 'blob'})
            .then(blob => {
              let link = document.createElement('a');
              let url = URL.createObjectURL(blob);
              link.download = fileName;
              link.href = url;
              this.$refs.bridge.appendChild(link);
              link.click();
              setTimeout(() => {
                URL.revokeObjectURL(url);
                this.$refs.bridge.removeChild(link);
              }, 150);
            })
            .catch(err => console.error(err));
          // window.location.href = `/security/user/tag/exportBatch?userIdsStr=${ids}`;
        }
        this.type = '';
      }
    },
    // 导出账号
    async exportAccount(type) {
      this.type = type
      let fileName = `${formatDate(safeNewDate(), 'YYYY-MM-DD')}`
      
      if (!type && this.multipleSelection.length <= 0) {
        return this.$platform.alert('请选择要导出的数据')
      }
      let ids = [];
      for (const user of this.multipleSelection) {
        ids.push(user.userId);
      }
      const planTaskIds = type ? [] : ids
      this.$refs.exportPanel.open(planTaskIds, fileName);
    },
    exportData() {
      let api = this.activeTypes.length > 0 ? '/security/user/taskRecord/exportBatch' : '/security/user/workState/exportBatch/new'
      let types = this.activeTypes.join(',');
      const [timeStart = '', timeEnd = ''] = this.selectdatetime || []
      const params = {
        [types ? 'createTimeStart' : 'timeStart']: timeStart,
        [types ? 'createTimeEnd' : 'timeEnd']: timeEnd,
      }

      if (export_state === 'all') {
        // 导出全部
        params.tagId = this.selectedDept?.id
        window.location.href = `${api}?${objectToUrlParams(params)}`
      } else {
        // 导出选中的
        params.userIdsStr = (this.multipleSelection || []).map(item => item.userId).join(',')
        // 新的导出接口
        let date = formatDate(safeNewDate(), 'YYYY-MM-DD');
        let fileName = `${date}${this.activeTypes.length ? this.$t('common.base.department') : this.$t('department.tips.memberMessage')}.xlsx`;
        this.$http.post(api, params, true, {responseType: 'blob'})
          .then(blob => {
            let link = document.createElement('a');
            let url = URL.createObjectURL(blob);
            link.download = fileName;
            link.href = url;
            this.$refs.bridge.appendChild(link);
            link.click();
            setTimeout(() => {
              URL.revokeObjectURL(url);
              this.$refs.bridge.removeChild(link);
            }, 150);
          })
          .catch(err => console.error(err));
      }
      export_state = '';
      this.selectionToggle();
      this.exportDialogClosed();
    },
    exportDialogClosed() {
      this.selectdatetime = [];
      this.exportDialogvisible = false;
    },
    userResetPwdConfirm(userId) {
      this.resetDialogvisible = true;
      this.resetForm.userId = userId;
    },
    resetDialogClosed() {
      this.resetForm.userId = '';
      this.resetForm.pwd = '';
      this.resetDialogvisible = false;
    },
    /* 钉钉端设置是否按 服务团队 还是钉钉通讯录 派单 */
    async setUsedAllot(setTag) {
      if (this.isAllotByDept) {
        this.isSeeAllOrg = false;
      }
      // setTag为true按通讯录 false按团队
      try {
        let params = {
          set: setTag ? 'dept' : 'tag'
        };
        let result = await TeamApi.usedAllot(params);

        if (setTag) {
          this.setSeeAllOrg();
        }

        if (result.status != 0) {
          return this.$platform.alert(result.message);
        }

        rootWindowInitDataData.allotByTag = !setTag
        setRootWindowInitData(rootWindowInitDataData)

      } catch (error) {
        console.log('setUsedAllot error: ', error);
      }
    },
    /* 是否开启 降低组织架构 */
    async setSeeAllOrg(state = false) {
      this.$track.clickStat(this.$track.formatParams('HIDE_NOT_SELF_DEPT_USER'));
      if (this.isSeeAllOrg) {
        this.isAllotByDept = false;
      }
      try {
        let params = {
          state
        };
        let result = await TeamApi.saveSeeAllOrg(params);
        if (result.status != 0) {
          this.$platform.alert(result.message);
        } else {
          this.isSeeAllOrg = state;
        }
      } catch (error) {
        console.log('setUsedAllot error: ', error);
      }
    },
    /* 是否开启 显示企业微信昵称 */
    async setNickname() {
      try {
        let res = await this.$http.post('/setting/nameConfig/update', { flag: this.isNickname }, false);
        const { status, message} = res;
        if (status != 0) return this.$platform.alert(message || this.$t('department.tips.switchFailed'))
        this.$platform.notification({
          title: message,
          type: 'success'
        });
        rootWindowInitDataData.IS_WECHAT_NAME = this.isNickname ? 1 : 0
        setRootWindowInitData(rootWindowInitDataData)
      } catch (error) {
        console.error('setNickname error: ', error);
      }
    },
    roleDialogClosed() {
      this.$refs.roleFormRef.resetFields();
    },
    async dispatchRole() {
      try {
        this.pending = true;
        const params = {
          state: this.roleForm.roleId != 0,
          roleId: this.roleForm.roleId
        };
        const { status, message } = await autoAuth(params);
        if (status !== 0)
          return this.$platform.notification({
            title: this.$t('department.tips.autoPermissionFailed'),
            message: message || '',
            type: 'error'
          });
        this.pending = false;
        this.roleDialogVisible = false;
        this.roleDialogClosed();
        this.$platform.notification({
          title: this.$t('department.tips.autoPermissionSuccess'),
          type: 'success'
        });
      } catch (error) {
        this.pending = false;
        console.error(error);
      }
    },

    createRole() {
      let fromId = window.frameElement.getAttribute('id');
      // this.$platform.openTab({
      //   id: 'create_role',
      //   title: '新建角色',
      //   close: true,
      //   url: '/security/role/create',
      //   fromId
      // });
      Platform.openAccurateTab({
        type: PageRoutesTypeEnum.PageCreateRole,
        fromId
      })
    },

    async resume(userId) {
      try {
        if (await this.$platform.confirm(this.$t('department.tips.recoverAccount'))) {
          const { status, message } = await http.post(
            '/security/user/resume',
            { userId },
            false
          );
          // if(status !== 0) this.$message.error(message || '');
          let isSucc = status == 0;
          this.$platform.notification({
            title: isSucc ? this.$t('common.base.success') : this.$t('common.base.fail'),
            message: isSucc ? this.$t('department.tips.recoverAccountSuccess') : message,
            type: isSucc ? 'success' : 'error'
          });
          isSucc && this.chooseRole(this.selectedRole);
        }
      } catch (error) {
        console.error(error);
      }
    },
    createTransTab(type, userId) {
      let fromId = window.frameElement.getAttribute('id');
      // this.$platform.openTab({
      //   id: 'M_JOBTRANSFER_DETAIL',
      //   title: '转交详情',
      //   close: true,
      //   url: `/jobtransfer/view?type=${type}&userId=${userId}`,
      //   fromId
      // });
      Platform.openAccurateTab({
        type: PageRoutesTypeEnum.PageJobtransferView,
        params: `type=${type}&userId=${userId}`,
        fromId
      })
    },
    async resetUserPwd() {
      const isValidate = await this.$refs.restFormRef.validate();
      if (!isValidate) return;

      let params = {};

      params.userId = this.resetForm.userId;
      params.password = md5(this.resetForm.pwd);
      resetPwdUpdateAdmin(params)
        .then(result => {
          let isSucc = result.status == 0;
          this.$platform.notification({
            title: isSucc ? this.$t('common.base.success') : this.$t('common.base.fail'),
            message: isSucc ? this.$t('common.base.resetPwdSuccess') : result.message,
            type: isSucc ? 'success' : 'error'
          });
          if (isSucc) this.resetDialogClosed();
        })
        .catch(err => console.log(err));
    },

    search(flag = false) {
      if(flag) this.visible = false;
      // 组织架构人员搜索
      this.initDeptUser(this.selectedDept);
      // this.$refs.loginUserBanDom.initData();
    },
    searchRole() {
      // 角色人员搜索
      this.rolePage.list = [];
      this.chooseRole(this.selectedRole);

    },
    chooseDelRole() {
      this.activeName = 'role';
      this.selectedDept = {};
      this.rolePage.list = [];
      let role = { id: -1, text: this.$t('department.tips.deletedAccount') };
      this.chooseRole(role);
    },
    async chooseRole(role) {
      this.multipleSelection = [];
      this.roleMultipleSelection = [];
      if (this.selectedRole.id != role.id) {
        this.roleKeyword = '';
      }
      this.selectedRole = role;
      this.roleLoading = true;
      // 获取角色下面的人员
      this.roleParams.keyword = this.roleKeyword;
      this.roleParams.roleId = '';
      this.roleParams.roleType = '';
      this.roleParams.pageNum = 1;
      this.roleParams.type = 0
      // this.rolePage.list = [];
      if (role.id == 0) {
        // 待分配账号
        this.roleParams.roleType = 'noauth';
        this.getBuyAndUseUserNumData(); // 已开通账号数量
      } else if (role.id == -1) {
        // 已删除账号
        this.roleParams.roleType = 'delauth';
      } else {
        this.roleParams.roleId = role.id;
      }
      return this.getRoleUserList(this.roleParams)
        .then(rolePage => {
          this.rolePage.merge(Page.as(rolePage));
          this.rolePage.list = rolePage.list || [];
          this.roleLoading = false;
        })
        .catch(err => console.error('err', err))
        .finally(() => (this.roleLoading = false));
    },

    getRoleUserList(params) {
      if (this.selectedRole.id == -1) return getDelUser(params);
      return getRoleUser(params);
    },
    getBuyAndUseUserNumData() {
      getBuyAndUseUserNum()
        .then(result => {
          let data = result.data || {};
          this.userCount = data.userCount || 0; // 已开通账号数量
          this.accountNum = data.accountNum || 0; // 账号总数量
          this.surplusNum = Number(data.accountNum) - Number(data.userCount) || 0;
        })
        .catch(err => console.log(err));
    },
    handleClick(tab, event) {
      if (tab.name === 'role') {
        this.chooseRole(this.selectedRole);
      }
    },
    handleClick1(tab, event) {
      this.params.pageNum = 1;
      if (tab.name === 'user') {
        // 请求成员信息
        this.fetchUser();
      } else if (tab.name === 'provider') {
        // 请求服务商信息
        this.$refs?.providerRef?.openServiceProvider(this.selectedDept.id, this.tableContainerHeight)
      } else {
        // 请求下级部门信息
        this.ChildTagList();
      }
      this.$nextTick(()=> {
        this.knowTableContainerHeight()
      })
    },
    addDepartment(br) {
      this.showParent = !!br;
      this.deptEditId = '';
      this.teamEditViewVisible = true;
      this.deptDialogVisible = true;
    },
    async delDepartment(id) {
      // 您删除的团队，如果包含子团队将会一并删除，是否继续？
      try {
        if (
          await this.$platform.confirm(
            this.$t('department.tips.deleteDepartmentAndChild')
          )
        ) {
          let ids = [this.selectedDept.id];
          if (id) ids = [id];

          let result = await TeamApi.deleteTag(ids);

          this.$platform.notification({
            type: result.status == 0 ? 'success' : 'error',
            title: `${this.$t('department.tips.deleteDepartment')}${result.status == 0 ? this.$t('common.base.success') : this.$t('common.base.fail')}`,
            message: result.status == 0 ? null : result.message
          });

          if (result.status == 0) {
            this.initialize(true);
          }
        }
      } catch (e) {
        console.error('teamDelete catch error', e);
      }
    },
    chooseChildDepartment(childDept) {
      this.selectedDept = childDept;
      this.initDeptUser(this.selectedDept);
    },
    chooseUser(type) {
      let options = {
        title: this.$t('department.tips.selectMember'),
        max: -1,
        selectedUser: this.userPage.list,
        mountEl: this.$el,
        showServiceProvider: false,
        typeServiceProvider: 0,
        mode: BaseSelectUserModeEnum.Filter,
      };

      this.$fast.select.multi.user(options)
        .then(result => {
          if (result.status == 0) {
            let users = result?.data?.users || [];

            if (type === 'role') {
              this.addRoleUserList(users);
            } else {
              this.addDeptUser(users);
            }
          }
        })
        .catch(err => console.error(err));
    },
    addDeptUser(users) {
      // 组织架构 添加成员
      let params = {
        tagId: this.selectedDept.id
      };
      params.userIds = users.map(item => item.userId);

      this.loading = true;

      TeamApi.addUser(params)
        .then(result => {
          let isSucc = result.status == 0;
          if (isSucc) {
            // 刷新组织架构 成员列表
            this.initialize(false);
          }
          this.$platform.notification({
            title: isSucc ? this.$t('common.base.success') : this.$t('common.base.fail'),
            message: isSucc ? this.$t('common.base.tip.addSuccess') : result.message,
            type: isSucc ? 'success' : 'error'
          });
        })
        .catch(err => console.log(err))
        .finally(() => (this.loading = false));
    },
    // 角色 添加成员
    addRoleUserList(users) {
      let params = {
        roleId: this.selectedRole.id
      };
      params.userIds = users.map(item => item.userId);
      this.loading = true;

      addRoleUser(params)
        .then(result => {
          let isSucc = result.status == 0;
          if (isSucc) {
            // 刷新列表
            this.chooseRole(this.selectedRole);
          }
          this.$platform.notification({
            title: isSucc ? this.$t('common.base.success') : this.$t('common.base.fail'),
            message: isSucc ? this.$t('common.base.tip.addSuccess') : result.message,
            type: isSucc ? 'success' : 'error'
          });
        })
        .catch(err => console.log(err))
        .finally(() => (this.loading = false));
    },
    /**
     * @deprecated 已废弃
    */
    /* 选择多个部门 / 调整部门 */
    chooseDepartmentMulti() {
      if (this.multipleSelection.length <= 0) {
        return this.$platform.alert(this.$t('department.tips.pleaseSelectAdjustMember'));
      }

      if (this.multipleSelection.length > 1) {
        return this.$platform.alert(this.$t('department.tips.pleaseSelectAdjustOneMember'));
      }

      let options = {
        title: this.$t('department.tips.selectDepartment'),
        seeAllOrg: true,
        max: -1
      };

      this.$fast.contact
        .choose('dept_only', options)
        .then(result => {
          let data = result.data || {};
          if (result.status == 0) {
            this.updateDepartmentUserBatch(data.depts || {});
          }
        })
        .catch(err => console.error(err));
    },
    /* 新建部门 */
    departmentCreate(form) {
      let { department } = form;
      let parent = this.getHigherDepartment(this, department);
      let params = {
        name: form.name,
        description: this.$t('department.tips.definedCreate'),
        type: 'app',
        parentId: parent.type == 'ding' ? department.dingId : department.id
      };

      this.loading = true;

      addDepartment(params)
        .then(result => {
          let isSucc = result.status == 0;

          if (isSucc) {
            this.initialize(false);
            this.$refs.departmentEditPanel.close();
          }

          this.$platform.notification({
            title: isSucc ? this.$t('common.base.success') : this.$t('common.base.fail'),
            message: isSucc ? this.$t('common.base.tip.createSuccess') : result.message,
            type: isSucc ? 'success' : 'error'
          });
        })
        .catch(err => console.error(err))
        .finally(() => (this.loading = false));
    },
    /* 编辑部门 */
    departmentEdit(form) {
      let { department } = form;
      let parent = this.getHigherDepartment(this, department);

      let params = {
        id: this.selectedDept.id,
        name: form.name,
        type: 'app',
        parentId: parent.type == 'ding' ? department.dingId : department.id
      };
      this.loading = true;

      updateDepartment(params)
        .then(result => {
          let isSucc = result.status == 0;

          if (isSucc) {
            this.$refs.departmentEditPanel.close();
            this.initialize();
          }

          this.$platform.notification({
            title: isSucc ? this.$t('common.base.success') : this.$t('common.base.fail'),
            message: isSucc ? this.$t('common.base.tip.updateSuccess') : result.message,
            type: isSucc ? 'success' : 'error'
          });
        })
        .catch(err => console.error(err))
        .finally(() => (this.loading = false));
    },
    /* 删除部门 */
    async departmentDelete() {
      if (!(await this.$platform.confirm(this.$t('department.tips.confrmDeleteDepartment')))) return;

      let params = {
        id: this.selectedDept.id
      };

      this.loading = true;

      deleteDepartment(params)
        .then(result => {
          let isSucc = result.status == 0;

          if (isSucc) {
            this.$refs.departmentEditPanel.close();
            this.initialize();
          }

          this.$platform.notification({
            title: isSucc ? this.$t('common.base.success') : this.$t('common.base.fail'),
            message: isSucc ? this.$t('common.base.deleteSuccess') : result.message,
            type: isSucc ? 'success' : 'error'
          });
        })
        .catch(err => console.log(err))
        .finally(() => (this.loading = false));
    },
    /** 抓取部门数据 */
    fetchDept() {
      let params = {
        seeAllOrg: this.isSeeAllOrg,
        keyword: this.deptKeyword
      };

      return TeamApi.tagV2List(params)
        .then(result => {
          return (result && result.list) || [];
        })
        .catch(err => console.error('err', err));
    },
    /* 抓取部门 人员数量 */
    fetchDeptCount() {
      return getDepartmentUserCount();
    },
    /** 抓取用户数据 */
    fetchUser:_.debounce(function(){
      let params = this.buildSearchParams();
      // 组织架构页面获取人员需要showNoRole为true
      this.userLoading = true;
      return TeamApi.getUserOrgList(params)
        .then(userPage => {
          this.userPage.merge(Page.as(userPage));
          this.userPage.list = userPage.list || [];
          
          this.rerenderDepartmentUserTable();

          // 解决中文环境下，操作拦高度和表格内容高度不一致的bug
          // this.$nextTick(() => {
          //   this.$refs.multipleTable.doLayout()
          // })
        })
        .catch(err => console.error('err', err))
        .finally(() => (this.userLoading = false))
    }, 500),
    /* 查询是否开启 降低组织架构的开关 */
    getSeeAllOrg() {
      return http.post('/setting/user/getSeeAllOrg').then(result => {
        return result;
      });
    },
    /* 跳转 用户详情页 */
    goUserDetail(id) {

      if (!window.frameElement) return;

      if (!this.globalIsHaveAccountViewAuth) return

      let fromId = window.frameElement.getAttribute('id');
      // this.$platform.openTab({
      //   id: `tab_department_view_${id}`,
      //   title: '成员详情',
      //   close: true,
      //   reload: true,
      //   url: `/security/user/view/${id}?from=department`,
      //   fromId
      // });
      Platform.openAccurateTab({
        type: PageRoutesTypeEnum.PageSecurityUserView,
        key: id,
        reload: true,
        params: 'from=department',
        fromId,
      })
    },
    getHigherDepartment(data, department) {
      let depts = data.depts;

      if (!Array.isArray(depts)) return {};

      let higherDepartment = depts.filter(dept => dept.id == department.id);

      if (higherDepartment.length > 0) return data;

      for (let i = 0; i < depts.length; i++) {
        let dept = depts[i];
        let subDepartments = dept.subDepartments || [];
        dept.depts = subDepartments;

        let higherDepartment = this.getHigherDepartment(dept, department);

        if (Object.keys(higherDepartment).length > 0) {
          return higherDepartment;
        }
      }

      return {};
    },
    handleSizeChange(pageSize) {
      this.params.pageSize = pageSize;
      this.params.pageNum = 1;

      let stash_data = storageGetLocal(pageSizeStorageKey) || '';
      stash_data = stash_data ? JSON.parse(stash_data) : {};
      storageSetLocal(pageSizeStorageKey, JSON.stringify({ ...stash_data,
        [this.activeName1]:pageSize
      }))

      this.fetchUser();
    },
    depthandleSizeChange(pageSize) {
      this.dept.pageSize = pageSize;
      this.dept.pageNum = 1;
      this.loading = true;

      let stash_data = storageGetLocal(pageSizeStorageKey) || '';
      stash_data = stash_data ? JSON.parse(stash_data) : {};
      storageSetLocal(pageSizeStorageKey, JSON.stringify({ ...stash_data,
        [this.activeName1]:pageSize
      }))

      this.ChildTagList().finally(() => (this.loading = false));
    },
    roleHandleSizeChange(pageSize) {
      this.roleParams.pageSize = pageSize;
      this.roleParams.pageNum = 1;

      this.roleLoading = true;

      return this.getRoleUserList(this.roleParams)
        .then(rolePage => {
          this.rolePage.merge(Page.as(rolePage));
          this.rolePage.list = rolePage.list || [];
          this.roleLoading = false;
        })
        .catch(err => console.error('err', err))
        .finally(() => (this.roleLoading = false));
    },
    /** 初始化 */
    initialize(isInit = true) {
      this.initializeDept(isInit);
    },
    /** 初始化部门数据 */
    async initializeDept(isInit = true) {
      this.loading = true;
      this.isSeeAllOrg = false;

      try {
        /* 如果开启 查询按组织架构选项 */
        let result = await this.getSeeAllOrg();
        this.isSeeAllOrg = result.data;
      } catch (error) {
        console.log('error: ', error);
      }

      let subtask = [this.fetchDept(), this.fetchDeptCount()];

      Promise.all(subtask)
        .then(result => {
          let depts = result[0] || [];
          let deptUserCount = result[1] || {};
          this.deptUserCount = deptUserCount.data || {};
          this.depts = depts;
          isInit && (this.allDepts = JSON.parse(JSON.stringify(depts)));
          this.initDeptUser(
            isInit ? this.depts[0] : _.cloneDeep(this.selectedDept)
          );
          this.$nextTick(()=> {
            this.knowTableContainerHeight()
            let that_ = this;
            window.onresize = _.debounce(()=>{
              that_.knowTableContainerHeight()
            }, 500)
          })
        })
        .catch(err => console.error(err));
    },
    /** 选中一个部门 */
    async initDeptUser(dept) {

      this.moreDropDownComponentKey = randomString()

      this.activeName = 'tag';
      this.multipleSelection = [];
      this.roleMultipleSelection = [];
      if (this.activeName == 'tag' && this.selectedRole.id == -1) {
        this.selectedRole = { id: '0', text: this.$t('department.tips.waitingMember') };
      }
      try {
        if (this.selectedDept.id != dept.id) {
          this.keyword = '';
        }
        this.selectedDept = dept;

        // 查询用户
        this.params.keyword = this.keyword;
        // 只有选择的不是主tag 搜索人员就不传tagid 后端返回主tag的parentId为null
        // if (dept.parentId) {
        //   this.params.tagId = dept.id;
        // } else {
        //   this.params.tagId = '';
        // }
        // http://zentao.shb.ltd/index.php?m=bug&f=view&bugID=26724&t=html&tid=2y630r00
        // 后端要求根部门也要传tagId
        this.params.tagId = dept.id;
        // this.params.departmentId = dept.id;
        this.params.pageNum = 1;
        this.params.type = 0
        this.params.seeAllOrg = this.isSeeAllOrg;
        this.fetchTeamData();
        await this.handleClick1({ name: this.activeName1 });
      } catch (error) {
        console.error(error);
      }

    },
    async fetchTeamData() {
      let _this = this;
      this.subDepartmentsPage.id = this.selectedDept.id;
      this.loading = true;
      try {
        let result = await TeamApi.getTag(_this.subDepartmentsPage);
        if (result.status)
          return this.$platform.notification({
            title: this.$t('common.base.fail'),
            message: result.message,
            type: 'error'
          });
        this.deptInfo = result.data;
        this.subDepartments = this.deptInfo.children || [];
        this.loading = false;
        // 翻译部门位置地址
        this.addressSwitch();
        // this.subDepartments.merge(Page.as(result));
      } catch (error) {
        console.log('error: ', error);
      }
    },

    // 翻译部门位置地址
    async addressSwitch(){
      let { tagAddress } = this.deptInfo;
      let key = getCountryKey(tagAddress)

      this.deptSiteAddressNameObj = await addressKeyToViewLanguage(key,tagAddress);
    },

    isRootDepartment(department = {}) {
      return this.allDepts.some(dept => dept.id == department.id);
    },
    jump(pageNum) {
      this.params.pageNum = pageNum;

      this.fetchUser();
    },
    deptjump(pageNum) {
      this.dept.pageNum = pageNum;

      this.loading = true;

      this.ChildTagList().finally(() => (this.loading = false));
    },
    roleJump(pageNum) {
      this.roleParams.pageNum = pageNum;

      this.roleLoading = true;

      return this.getRoleUserList(this.roleParams)
        .then(rolePage => {
          this.rolePage.merge(Page.as(rolePage));
          this.rolePage.list = rolePage.list || [];
          this.roleLoading = false;
        })
        .catch(err => console.error('err', err))
        .finally(() => (this.roleLoading = false));
    },
    nodeRender(h, node) {
      const { source, tagName, weChatDeptId, userCount, dingId } = node
      let content;
      if(this.tenantType == 2 && dingId) {
        content = (<span><open-data type="departmentName" openid={dingId}></open-data>（{userCount || 0}）</span>)
      } else {
        content = (<span>{tagName}（{userCount || 0}）</span>);
      }
      let count = this.deptUserCount[node.id] || 0;
      if (count <= 0) return content;
      if(this.tenantType == 2 && dingId) {
        return (
          <div class="dept-node-wrap">
            <span class="dept-node-name"><open-data type="departmentName" openid={dingId}></open-data></span>
            <span class="dept-node-count">&nbsp;({count})({this.$t('department.tips.unitPeople')})</span>
          </div>
        );
      }
      return (
        <div class="dept-node-wrap">
          <span class="dept-node-name">{tagName}</span>
          <span class="dept-node-count">&nbsp;({count})({this.$t('department.tips.unitPeople')})</span>
        </div>
      );
    },
    async openCreateUserPanel(row) {
      try {
        await this.getInternalAccountInfo({userId: row?.userId})
      } catch (error) {
        console.log('error', error)
      }
      if (row) {
        let obj = JSON.parse(JSON.stringify(row));
        obj.dateTime = safeNewDate().getTime();
        this.userRow = JSON.stringify(obj);
      } else {
        this.userRow = '';

        setTimeout(()=>{
          this.$refs.createUserPanel.form.tagList = [this.selectedDept];
        }, 0)
      }
      this.createUserPanelVisible = true;
      this.userDialogVisible = true;
      // this.$refs.createUserPanel.open({});
    },
    openDepartmentEditPanel(row) {
      // let data = {
      //   name: this.selectedDept.name,
      //   higherDepartment: this.getHigherDepartment(this, this.selectedDept)
      // }
      // this.$refs.departmentEditPanel.open('edit', data);
      // 部门编辑就是之前的团队编辑
      // window.location.href = `/security/tag/editTag/${this.selectedDept.id}`
      // id 有值说明是子部门编辑
      // let fromId = window.frameElement.getAttribute('id');
      // let isRoot = !this.selectedDept.parentId; // 判断是不是根部门，根部门编辑不能修改名称
      // platform.openTab({
      //   id: 'editTag',
      //   title: '编辑部门',
      //   url: id
      //     ? `/security/tag/editDept/${id}`
      //     : `/security/tag/editDept/${this.selectedDept.id}?isRoot=${isRoot}`,
      //   reload: true,
      //   fromId
      // });
      this.deptEditId = row.id;
      this.showParent = false;
      this.teamEditViewVisible = true;
      this.deptDialogVisible = true;
    },
    /** select dept person */
    selectionHandle(selection) {
      this.multipleSelection = selection.slice();
    },
    selectionToggle(rows) {
      if (rows) {
        rows.forEach(row => {
          this.$refs.multipleTable.toggleRowSelection(row);
        });
      } else {
        this.$refs.multipleTable.clearSelection();
        this.multipleSelection = [];
      }
    },
    /** select role person */
    roleSelectionHandle(selection) {
      this.roleMultipleSelection = selection.slice();
    },
    roleSelectionToggle(rows) {
      if (rows) {
        rows.forEach(row => {
          this.$refs.roleMultipleTable.toggleRowSelection(row);
        });
      } else {
        this.$refs.roleMultipleTable.clearSelection();
        this.roleMultipleSelection = [];
      }
    },
    handleSelection(selection) {

      let tv = this.computeSelection(selection);
      let original = this.multipleSelection.filter(ms =>
        this.userPage.list.some(cs => cs.userId === ms.userId)
      );
      let unSelected = this.userPage.list.filter(c =>
        original.every(oc => oc.userId !== c.userId)
      );

      if (tv.length > this.selectedLimit) {
        this.$nextTick(() => {
          original.length > 0
            ? unSelected.forEach(row => {
              this.$refs.multipleTable.toggleRowSelection(row, false);
            })
            : this.$refs.multipleTable.clearSelection();
        });
        return this.$platform.alert(this.$t('common.base.tip.maxDataCanChooseTips', { data1: this.selectedLimit }));
      }

      this.multipleSelection = tv;
    },
    computeSelection(selection) {
      let tv = [];
      tv = this.multipleSelection.filter(ms =>
        this.userPage.list.every(c => c.userId !== ms.userId)
      );
      tv = _.uniqWith([...tv, ...selection], _.isEqual);
      return tv;
    },
    toggleSelection(rows) {
      let isNotOnCurrentPage = false;
      let row = undefined;

      if (rows) {
        for (let i = 0; i < rows.length; i++) {
          row = rows[i];
          isNotOnCurrentPage = this.userPage.list.every(item => {
            return item.userId !== row.userId;
          });
          if (isNotOnCurrentPage) return;
        }
        rows.forEach(row => {
          this.$refs.multipleTable.toggleRowSelection(row);
        });
      } else {
        this.$refs.multipleTable.clearSelection();
        this.multipleSelection = [];
      }
    },
    matchSelected() {

      if (!this.multipleSelection.length) return;

      const selected = this.userPage.list.filter(c => {

        if (this.multipleSelection.some(sc => sc.userId === c.userId)) {

          this.multipleSelection = this.multipleSelection.filter(
            sc => sc.userId !== c.userId
          );

          this.multipleSelection.push(c);

          return c;
        }

      }) || [];

      this.$nextTick(() => {
        this.toggleSelection(selected);
      });
    },
    async roleDeleteConfirm() {
      // 角色 批量移除成员
      if (this.roleMultipleSelection.length <= 0) {
        return this.$platform.alert(this.$t('department.tips.selectRemoveMember'));
      }
      let hasSuperAdmin = this.roleMultipleSelection.some(user => {
        return user.superAdmin == 2;
      });
      if (hasSuperAdmin) {
        return this.$platform.alert(
          this.$t('department.tips.removeMemberFailed')
        );
      }
      if (await this.$platform.confirm(this.$t('department.tips.confirmRemoveMember'))) {
        this.roleUserDelete();
      }
    },
    roleUserDelete() {
      let params = {
        userIds: this.roleMultipleSelection.map(item => item.userId).join(','),
        roleId: this.selectedRole.id
      };

      this.loading = true;

      delRoleUser(params)
        .then(result => {
          let isSucc = result.status == 0;

          if (isSucc) {
            this.chooseRole(this.selectedRole);
          }

          this.$platform.notification({
            title: isSucc ? this.$t('common.base.success') : this.$t('common.base.fail'),
            message: isSucc ? this.$t('common.base.removeSuccess') : result.message,
            type: isSucc ? 'success' : 'error'
          });
        })
        .catch(err => console.log(err))
        .finally(() => (this.loading = false));
    },
    async userDeleteConfirm(type) {
      // 批量删除
      if (type === 'multiple' && this.multipleSelection.length <= 0) {
        return this.$platform.alert(this.$t('department.tips.selectRemoveMember'));
      }

      if (await this.$platform.confirm(this.$t('department.tips.removeMemberFromDepartment'))) {
        this.userDelete();
      }
    },
    userDelete() {
      let params = {
        userIds: this.multipleSelection.map(item => item.userId).join(','),
        tagId: this.selectedDept.id
      };

      this.loading = true;

      TeamApi.deleteUser(params)
        .then(result => {
          let isSucc = result.status == 0;

          if (isSucc) {
            this.initialize(false);
          }

          this.$platform.notification({
            title: isSucc ? this.$t('common.base.success') : this.$t('common.base.fail'),
            message: isSucc ? this.$t('common.base.removeSuccess') : result.message,
            type: isSucc ? 'success' : 'error'
          });
        })
        .catch(err => console.log(err))
        .finally(() => (this.loading = false));
    },
    userAdd(form = {}) {
      let params = JSON.parse(JSON.stringify(form));
      if (!form.userId) {
        params.loginPassword = md5(params.pass);
      }
      params.roles = params.role.map(r => ({ id: r })) || [];
      if(this.haveUserNote){
        params.createNeedNote = this.createNeedNote;
      }

      this.loading = true;

      createAndAddDepartmentUser(params)
        .then(result => {
          let isSucc = result.status == 0;

          if (isSucc) {
            this.createUserPanelVisible = false;
            this.userDialogVisible = false;
            this.initialize(false);
          }

          this.$platform.notification({
            title: isSucc ? this.$t('common.base.success') : this.$t('common.base.fail'),
            message: isSucc ? this.$t('common.base.tip.operationSuccess') : result.message,
            type: isSucc ? 'success' : 'error'
          });
        })
        .catch(err => console.log(err))
        .finally(() => (this.loading = false));
    },
    updateDepartmentUserBatch(departments) {
      let params = {
        userId: this.multipleSelection[0].userId,
        departmentIds: departments.map(d => d.id).join(',')
      };

      this.loading = true;

      updateDepartmentUserBatch(params)
        .then(result => {
          let isSucc = result.status == 0;

          if (isSucc) {
            this.initialize(false);
          }

          this.$platform.notification({
            title: isSucc ? this.$t('common.base.success') : this.$t('common.base.fail'),
            message: isSucc ? this.$t('common.base.tip.adjustSuccess') : result.message,
            type: isSucc ? 'success' : 'error'
          });
        })
        .catch(err => console.log(err))
        .finally(() => (this.loading = false));
    },

    // 构建搜索参数
    buildSearchParams() {
      const advancedSearchParams = this.$refs.searchPanel ? this.$refs.searchPanel.buildParams() : {};
      const {tags, roleIds, enabled, labelIds} = advancedSearchParams;
      const { pageNum, pageSize, keyword, tagId } = this.params

      return {
        currTagId: tagId,
        pageNum,
        pageSize,
        keyword,
        enabled: enabled ? Number(enabled) : undefined,
        tagIdList: (tags || []).map(x=>x.id),
        roleIdList: (roleIds || []).filter(x=> x !== RoleType),
        labelIdList: labelIds,
      }
    },
    // 高级搜索
    panelSearchAdvancedToggle() {
      this.getRoleList();
      this.getBaseLabelList();
      this.visible = true;
    },
    // 设置高级搜索展示列数
    setAdvanceSearchColumn(command) {
      this.columnNum = Number(command);
    },
    // 重置
    resetParams() {
      window.location.reload()
    },
    // 获取角色列表
    getRoleList(){
      getRoleTree()
        .then( result => {
          if(!result || !result.data || !result.data.children || result.data.children.length < 2)
            return false

          if(result.data.children[1].type === 'assigned'){
            let roles = result.data.children[1].children;
            this.rolesList = roles.map(role => ({ text: role.roleName, value: role.roleId }));
            this.rolesList.unshift({ text: this.$t('common.base.null'), value: RoleType })
          }
        })
        .catch((err) => console.error(err));
    },
    // 获取标签数据
    getBaseLabelList(){
      getBaseLabelList().then(res=>{
        const { status, data, message } = res;
        if(status !== 0) return;

        this.baseLaberlList = data.map(x=>({text: x.tagName, value: x.id}));
      })
    },
    /**
     * @des 表单拖拽钩子函数
     */
    headerDragend(newWidth, oldWidth, column, event) {
      let stash_data = storageGetLocal('notStandardTableStash') || '';
      stash_data = (stash_data && JSON.parse(stash_data)) || {};
      this.$set(this[`tableListForWidthStash${this.activeName1}`], column.property, {width:`${column.width}px`});
      stash_data[`${this.tableStashKey}${this.activeName1}`] = this[`tableListForWidthStash${this.activeName1}`];
      storageSetLocal('notStandardTableStash', JSON.stringify(stash_data));
    },
    /**
     * @des 初始化表格宽度函数
     */
    buildColumn(){
      try {
        let stash_data = storageGetLocal('notStandardTableStash');
        stash_data = stash_data && JSON.parse(stash_data);
        let pageStash = stash_data[`${this.tableStashKey}${this.activeName1}`] || {};
        this.$set(this, `tableListForWidthStash${this.activeName1}`, {...this[`tableListForWidthStash${this.activeName1}`], ...pageStash});
      } catch (error) {
        console.warn(error, 'error try catch');
      }

    },
    async actionMany(type){
      if (this.multipleSelection.length <= 0) {
        return this.$platform.alert(this.$t('department.tips.switchMemberStatus', {status: type == 'enable' ? this.$t('common.base.enable') : this.$t('common.base.disable')}))
      }
      if (await this.$platform.confirm(this.$t('department.tips.batchMemberStatus', {status: type == 'enable' ? this.$t('common.base.enable') : this.$t('common.base.disable')}))) {
        this.userEnable(type);
      }
    },
    userEnable(type){
      let params = this.multipleSelection.map(item => item.userId)
      if(type == 'enable'){

        TeamApi.enableMany(params)
          .then(result => {
            let isSucc = result.status == 0;
            if (isSucc) {
              this.initialize(false);
            }
            this.$platform.notification({
              title: isSucc ? this.$t('common.base.success') : this.$t('common.base.fail'),
              message: isSucc ? this.$t('common.base.batchEnableSuccess') : result.message,
              type: isSucc ? 'success' : 'error'
            });
          })
          .catch(err => console.log(err))
          .finally(() => (this.loading = false));
      }else{
        TeamApi.unableMany(params)
          .then(result => {
            let isSucc = result.status == 0;
            if (isSucc) {
              this.initialize(false);
            }
            this.$platform.notification({
              title: isSucc ? this.$t('common.base.success') : this.$t('common.base.fail'),
              message: isSucc ? this.$t('common.base.batchDisableSuccess') : result.message,
              type: isSucc ? 'success' : 'error'
            });
          })
          .catch(err => console.log(err))
          .finally(() => (this.loading = false));
      }
    },

    // 下载批量更新模板
    downloadTem(){
      if (!this.multipleSelection.length)
        return this.$platform.alert(this.$t('department.tips.pleaseSelectMember'));
      let date = formatDate(safeNewDate(), 'YYYY-MM-DD');
      let fileName = `${date}${this.$t('department.tips.memberMessage')}.xlsx`;
      let url = '/security/user/updateTemplateExport/new';
      let userIdsStr = [];
      for (const user of this.multipleSelection) {
        userIdsStr.push(user.userId);
      }
      // userIdsStr = userIdsStr.join(',');
      let params = {
        userIdList: userIdsStr,
      }
      this.$http.post(url, params, true, {responseType: 'blob'})
        .then(blob => {
          let link = document.createElement('a');
          let url = URL.createObjectURL(blob);
          link.download = fileName;
          link.href = url;
          this.$refs.bridge.appendChild(link);
          link.click();
          setTimeout(() => {
            URL.revokeObjectURL(url);
            this.$refs.bridge.removeChild(link);
          }, 150);
        })
        .catch(err => console.error(err));
    },
    /**
     * @des 获取列表当前的可滚动高度
     */
		 knowTableContainerHeight(){
      let min = 440;
      let delMin = 440;
      try {
        let window_ = window.innerHeight;
        let header = this.$refs.tableHeaderContainer?.offsetHeight || 0;
        // let do_ = this.$refs.tableDoContainer?.offsetHeight || 0;
        // let footer = this.$refs.tableFooterContainer?.offsetHeight || 0;
        let selection = this.$refs.BaseSelectionBarComponent?.offsetHeight || 0;
        // selection = selection ? selection + 8 : selection;
        min = window_ - header * 1 - selection * 1  - 20 - 12 - 40 - 66 - 56;
        delMin =  window_ - 20 - 64 - 56;
        console.log(min, 'min')
        min = min > 440 ? min : 440;
        delMin = delMin > 440 ? delMin : 440;
      } catch (error) {
        console.warn(error, 'error try catch');
      }
      this.$set(this, 'delTableContainerHeight', `${delMin}px`)
      this.$set(this, 'tableContainerHeight', `${min}px`)
    },
    changePackUp(){
      this.packUp = !this.packUp;
      this.$nextTick(()=>{
        this.knowTableContainerHeight()
      })
    },
    rerenderDepartmentUserTable() {
      this.$nextTick(() => {
        this.departmentUserTableKey = randomString();
        this.$nextTick(()=> {
          this.matchSelected()
        })
      });
    }

  },
  components: {
    [CreateUserPanel.name]: CreateUserPanel,
    [DepartmentEditPanel.name]: DepartmentEditPanel,
    [ModifyName.name]: ModifyName,
    [TeamEditView.name]: TeamEditView,
    [BaseSearchDrawer.name]: BaseSearchDrawer,
    [BaseSearchPanel.name]: BaseSearchPanel,
    [ChangeDialog.name]: ChangeDialog,
    [ServiceProviderTab.name]: ServiceProviderTab,
    LoginUserBan,
  }
};
</script>

<style lang="scss">
.el-form-item--small.el-form-item{
  margin-bottom: 16px;
}
.department-detail-header-title-box.department-detail-header-title span{
  margin-right:0;
  font-weight: normal;
}
.add-dialog-container.service_body{
  padding:10px;
  z-index:2000;
  .el-form.demo-ruleForm{
    width: 98%;
    overflow:hidden;
    padding-top:10px
  }
  .base-modal.transition__container{
    max-height: calc(100% - 120px);
    max-height: calc(100vh - 120px);
  }
}
.dialog_body{
  .el-dialog__body{
    height: 500px;
    overflow-y: auto;
  }
}
.department-main-right_bgFFF.department-main-right {
  .department-user-block {
    padding: 0 10px 0 10px;
    border-radius: 4px;
    background: #fff;
    position:relative;
  }
}
.el-tabs__header {
  position:sticky;
  top:0;
  z-index:99;
  background:#fff;
  margin-left: -1px;
      margin: 0;
}
.el-tabs__content {
  min-width: 300px;
}

.collapse {
 span {
    padding: 5px;
    cursor: pointer;
    color: #666;
  }
  div{
    height: 53px;
    border-top: none;
    i.iconfont.icon-mianbanjiantou{
      font-size:18px;
    }
  }
}

.el-tabs-expand {
  width: 400px;
}

.dept-search {
  display: flex;
  align-items: center;
  width: 100%;
  align-content: center;
  margin-top: 16px;
  .el-input {
    margin: 0 20px;
  }
  .dept-add {
    color: $color-primary-light-6;
    font-size: 30px;
    margin-right: 20px;
    cursor: pointer;
    i{
      position:relative;
      top:-3px
    }
  }
}

.dept-search-border {
  // border-top: solid 1px #d9d9d9;
  padding-top: 10px;
}

.dept-header-see {
  width: 290px;
  margin-top: 10px;
  margin-bottom: 10px;
  margin-left: 10px;
  display: flex;
  align-items: center;
  white-space: initial;
}
.dept-role-item {
  &:hover,
  &.department-role-selected {
    background-color: $color-primary-hover !important;
    color: $color-primary;
  }
}
.dept-del-role-item {
  flex: 1;
  position: absolute;
  bottom: 0;
  width: 100%;
  margin-top: 10px;
  border-top: 1px solid #eee;
}
.department-child-item.dept-del-tag-item {
  bottom: 44px;
  line-height: 0;
  height: auto;
  border: none;
  background: #fff;
  margin-bottom: 10px;
  .dept-header-see {
    margin-top: 0;
  }
}


 .form-view-row-content-address:hover span{
     color:#333
    }
.text-center {
  display: block;
  text-align: center;
  color: $color-primary-light-6;
}
.create-role {
  display: flex;
  justify-content: flex-end;
  margin-bottom: 10px;
  margin-right: 10px;
}

.dept-search-group {
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  padding:16px 0;
  .dept-search-group-left {
    display: flex;
    input {
      height: 34px;
      line-height: 34px;
    }
    button {
      margin-right: 8px;
    }

    .advanced-search-btn{
      margin-right: 12px;
      @include fontColor;
    }
  }
  .el-dropdown {
    padding: 4px 15px;
    margin-left: 8px;
    font-size: 14px;
    border-radius: 4px;
    outline: none;
    line-height: 24px;
    cursor: pointer;
  }
}

.department-main-right {
  .margin-top-0 {
    margin-top: 0;
  }
}
.department-user-header-total-top {
  display: flex;
  justify-content: space-between;
  line-height: 55px;
  border-bottom: 1px solid #e8e8e8;
  .title {
    font-size: 20px;
    color: #262626;
  }
  .surplus {
    color: #ff4d4f;
  }
  .margin-letft-24 {
    margin-left: 24px;
  }
  span {
    color: #595959;
  }
}
.department-user-header-total-bottom {
  line-height: 40px;
  margin-bottom: 12px;
  color: #595959;
}

.dept-edit-del {
  button {
    padding: 4px 15px;
    margin-left: 8px;
  }
}

.super-admin-label {
  background: rgba(255, 146, 0, 0.16);
  border-radius: 4px;
  border: 1px solid rgba(255, 146, 0, 0.16);
  color: #FF9200;
  padding: 0px 10px;
  font-size: 10px;
  display: inline-block;
  height: 24px;
  line-height: 24px;
  margin: 8px 5px;
}
.super-admin-label-auto{
  background: $color-primary-light-1;
border: 1px solid $color-primary-light-1;
color:$color-primary-light-6
}
.reset-dialog-form {
  label {
    margin-bottom: 20px;
  }
}

html,
body,
.department-container {
  height: 100%;
}
body {
  padding: 10px;
  min-width: 1100px;
}

.department-container {
  background: #edf0f5;
  border-radius: 3px;
  box-shadow: 0 1px 4px rgba(216, 216, 216, 0.65);

  display: flex;
  flex-flow: column nowrap;
}

.department-main {
  display: flex;
  flex-flow: row nowrap;
  flex: 1;

  height: 100%;
  position: relative;
}

.department-main-left {
  display: flex;
  flex: 2;
  flex-flow: column nowrap;

  min-width: 300px;
  height: 100%;

  .bc-dept {
    width: 100%;
  }

  .base-tree-node-content {
    line-height: 32px;
  }

  .base-tree-node-arrow {
    width: 35px;
  }
}

.department-main-left-dd {
  height: calc( 100% - 46px);
}

.department-main-right {
  background: #fff;
  border-radius: 2px;
  flex: 1;
  height: 100%;
  min-width: 400px;
  display:flex;
  flex-direction:column;
  overflow-y:auto;
}

.department-tree-view {
  flex: 1;
  padding-top: 5px;
  // overflow-y: auto;
}

.department-detail-header {
  border-radius: 4px;
  padding: 16px;
  background: #fff;
  &-title {
    display: flex;
    justify-content: space-between;
    line-height: 34px;

    span.title {
      font-size: 18px;
      font-weight: bold;

      margin-right: 30px;
    }
  }
}

.department-child-block {
  background: #fff;
  &-header {
    margin-bottom: 10px;
  }
}

.department-child-block,
.department-user-block {
  &-header {
    display: flex;
    justify-content: space-between;

    &-text {
      i {
        font-size: 20px;
      }
      span {
        font-size: 18px;
        font-weight: bold;
      }
    }

    &-btn {
    }
  }
}

.active-btn {
  cursor: pointer;
  color: rgb(15, 118, 139);
}

.department-user-table {
  position:relative;
  .view-detail-btn {
    color: $color-primary;
    display: inline-block;
    min-width: 52px;
    // max-width: 140px;
    @include text-ellipsis();
    .open-data {
      color: $color-primary;
    }
  }
  .icon-people {
    font-size: 14px;
  }
  .table-footer {
    display: flex;
    justify-content: space-between;

    padding: 10px;

    background: #fff;
    border-radius: 0 0 3px 3px;

    .list-info {
      font-size: 13px;
      line-height: 32px;
      margin: 0;
      color: #767e89;
    }
    .el-pagination {
      white-space: nowrap;
      padding: 2px 5px;
      color: #303133;
      font-weight: bold;
    }
    .selectedCount {
      color: $color-primary;
      padding: 0 3px;
      width: 15px;
      text-align: center;
    }
    .select-init-text:hover {
      cursor: pointer;
    }
  }

  // .cell{
  //   overflow: ;
  // }
  .information-table{
    .el-button{
        padding:4px;
      }
    .el-table__row td .cell,.el-table__header thead tr th .cell{
      // height:auto;
    }
    .el-table__fixed-right{
      .el-button + .el-button{
        margin-left:0px;
      }

    }

  }
}
.no-data-block {
  line-height: 30px;
  margin-top: 10px;
  text-align: center;
  color: #595959;
   font-size: 14px;
   padding-bottom:12px;
  .service-no-icon{
  display: block;
  height: 134px;
  margin: 32px auto 16px;
}
}

.department-child-item {
  border-bottom: 1px solid #eee;
  cursor: pointer;

  display: flex;
  justify-content: space-between;

  line-height: 44px;
  padding: 0 20px;
  background: #fff;
  &:hover {
    background-color: #fafafa;
  }
}
.el-tabs.dept-tabs {
  background: #fff;
  padding: 0 20px;
  border-radius: 4px;
  .el-tabs__nav-wrap::after{
    height: 1px;
  }
}
.department-left {
  width: 308px;
  position: relative;
  background: #fff;
  border-radius: 4px;
  border-top-right-radius: 0;
  .base-button {
    margin: 14px 20px 0;
    width: 268px;
    display: flex;
    align-items: center;
    justify-content: center;
    span {
      display: block;
      @include text-ellipsis;
    }
  }
}
.department-state {
  .el-tabs__content {
    height: calc(100% - 94px);
  }
}
.base-modal-mask {
  z-index: 5000;
}
.amap-sug-result {
  z-index: 5001;
}
.el-tabs{
  .el-tabs__content{
    overflow:visible !important;
  }
}

.reset-dialog-form-dialog {
  .el-dialog__body {
    padding-bottom: 50px;
  }
}
</style>
<style lang="scss" scoped>
.disable-popover, .transfer-btn {
  margin-left: 12px;
}
.disable-text {
  cursor: not-allowed;
  color: #c0c4cc !important;
}
.dept-info {
  display: flex;
  padding:6px 0;
  align-items: center;
  .form-view-col{
    display: flex;
    justify-content: flex-start;
    color: #262626;
    padding-right:24px;
    p{
      margin:0;
      line-height:20px
    }
    .form-view-col-content{
      text-overflow: ellipsis;
    white-space: nowrap;
    overflow: hidden;
    .form-view-col-content-address{
     cursor:auto;
    }
    }
  }
}
.form-view-row-content{
  width:100%
}

.department-container {
  ::v-deep .v-step[data-v-7c9c03f0] {
    background: #fff !important;
    color: #333 !important;
    -webkit-filter: drop-shadow(
      0px 9px 28px 8px rgba(0, 0, 0, 0.05)
    ) !important;
    filter: drop-shadow(0px 9px 28px 8px rgba(0, 0, 0, 0.05)) !important;
    padding: 0 !important;
    min-width: 240px !important;
    max-width: 350px !important;
  }

  ::v-deep .v-step .v-step__arrow[data-v-7c9c03f0] {
    border-color: #fff;
    border-left-color: transparent !important;
    border-right-color: transparent !important;
  }

  .tour-content-box {
    position: relative;
    overflow: hidden;
    padding: 0 20px;
    border-radius: 4px;

    .tour-left-tips {
      width: 80px;
      height: 32px;
      background: $color-primary;
      color: #fff;
      position: absolute;
      left: -40px;
      top: 0px;
      line-height: 40px;
      font-size: 12px;
      transform-origin: center top;
      transform: rotateZ(-45deg);
      text-align: center;
    }

    .tour-content {
      .tour-content-head {
        padding-top: 32px;
        padding-bottom: 10px;

        .iconfont {
          font-size: 10px;
          margin-bottom: 2px;
          color: #999;
          cursor: pointer;
        }
      }

      .tour-content-con {
        text-align: start;
        padding-bottom: 12px;
        color: #666;
      }
    }
  }

  .tour-bottom {
    height: 52px;
    padding: 0 20px;
    display: flex;
    justify-content: flex-end;
    align-items: center;

    .btns {
      width: 60px;
      height: 28px;
      background: $color-primary;
      color: #fff;
      text-align: center;
      line-height: 28px;
      border-radius: 4px;
    }

    .text {
      color: $color-primary;
    }

    :nth-child(n) {
      cursor: pointer;
    }

    :not(:last-child) {
      margin-right: 12px;
    }
  }

  /* 向上的箭头 */

  .normal-arrow-top {
    font-size: 0;
    line-height: 0;
    border-width: 0.5rem;
    border-color: #fff;
    width: 0;
    border-top-width: 0;
    border-style: dashed;
    border-bottom-style: solid;
    border-left-color: transparent;
    border-right-color: transparent;
    position: absolute;
    top: -0.5rem;
  }

  .guide-model-box {
    position: fixed;
    width: 100%;
    height: 100vh;
    top: 0;
    left: 0;
    background: rgba(0, 0, 0, 0.5);
    z-index: 996;
  }

  .guide-point {
    z-index: 997;
    position: sticky;
  }

  .bg-w {
    background: #fff;
  }

  .dept-step-1-box {
    position: absolute;
    top: 0;
    z-index: 997;
  }
}
.form-view-row-content-address {
  cursor: pointer;
}
.form-view-row-content-address:hover {
  color: $color-primary-light-6;
}
.dept-title {
  color: $color-primary-light-6;
  height: 35px;
  box-sizing: border-box;
  line-height: 40px;
  font-size: 14px;
  font-weight: 500;
  text-align: center;
  margin-top: 10px;
}
.department-detail-header-title{
  margin-bottom: 12px;
  font-size:16px
}

.dept-scroll-box{
  &::-webkit-scrollbar-track{
    background-color:#fff;
  }
}

.cur-point {
  color: $color-primary-light-6;
}
.lang-select-dropdown {
  margin-top: 0!important;
}
.el-dropdown-menu__item.is-disabled {
  color: #BFBFBF
}

.product-selected-count {
  color: $color-primary;
  padding: 0 3px;
  width: 15px;
  text-align: center;
  cursor: pointer;
  font-size: 13px;
}
</style>

<style lang="scss">
@import '@src/modules/dept/common.scss';
.department-container {
  .base-search-panel {
    .form-item-control {
      .biz-role-select .el-select {
        width: 100%;
      }
    }
  }
}
</style>

